EzDevInfo.com

backbone

Give your JS App some Backbone with Models, Views, Collections, and Events Backbone.js

What are the key differences between Meteor, Ember.js and Backbone.js? [closed]

Learning Ember.js / Backbone.js has been on my to-do list for a while. Now that Meteor is out, I am just wondering if anyone with experience of Meteor, Ember.js and Backbone.js can summarize the key differences and pros and cons of these three JavaScript frameworks for a person without any experience for any of them.

Specifically, I would like to know which tasks each framework is more suitable for, and why the others aren't.

Edit: now that I read a little bit more on Meteor, it seems to be more similar to Knockout.js rather than Backbone.js. So any comparison with Knockout.js is welcome too.


Source: (StackOverflow)

What is the purpose of backbone.js?

I tried to understand the utility of backbone.js from its site http://documentcloud.github.com/backbone, but I still couldn't figure out much.

Can anybody help me by explaining how it works and how could it be helpful in writing better JavaScript?


Source: (StackOverflow)

Advertisements

JavaScript I18n (internationalization) frameworks/libraries for client-side use? [closed]

We are currently creating a JavaScript application with backbone.js, and we need it translated or at least to support internationalization (I18n) in the future.

I've been looking around and found many libraries that help; Some are fairly simple where others seem overly complex. I found these in the past few hours:

Are there some blogs or sites that compare such frameworks? I would like to see if others already pointed out the pluses or pitfalls on any of these libraries.

We created our app module based on Require.js so if it has module support, that's definitely a plus.

Another requirement would be setting the locale after initialization, after we fetch the data from a webservice. We can't store static JSON files, except maybe for a default language, with the app. The translations come from a database and need to be sent to the app via a webservice, so we need to set the localization data dynamically instead of through JSON files. This is supported at least in Jed and i18next and jsperanto, but most likely also in others. In any case the app must never be blocked from execution.

I'm asking for help deciding which library suits best.


Something I noticed that is already missing in Jed, is providing a graceful alternative when a translation is not present in the locale dictionary. Jed just throws an error, something I find disturbing.

I prefer a cleaner way of handling missing translations, either provide a default string, print the key back to the screen. Additionally, but definitely not required, one could have the feature like i18next has, to post missing translations to a webservice. Though we won't need this, it is a nice feature.


Source: (StackOverflow)

Backbone View: Inherit and extend events from parent

Backbone's documentation states:

The events property may also be defined as a function that returns an events hash, to make it easier to programmatically define your events, as well as inherit them from parent views.

How do you inherit a parent's view events and extend them?

Parent View

var ParentView = Backbone.View.extend({
   events: {
      'click': 'onclick'
   }
});

Child View

var ChildView = ParentView.extend({
   events: function(){
      ????
   }
});

Source: (StackOverflow)

backbone.js - events, knowing what was clicked

In one of my backbone.js view classes, I have something like:

...

events: {
  'click ul#perpage span' : 'perpage'
},

perpage: function() {
  // Access the text of the span that was clicked here
  // Something like: alert($(element).text())
},

...

because my per page markup might have something like:

<ul id="perpage">
  <li><span>5</span></li>
  <li><span>10</span></li>
</ul>

So how exactly can I find information about the element that caused the event? Or in this instance, that was clicked?


Source: (StackOverflow)

Nested Models in Backbone.js, how to approach

I've got the following JSON provided from a server. With this, I want to create a model with a nested model. I am unsure of which is the way to achieve this.

//json
[{
    name : "example",
    layout : {
        x : 100,
        y : 100,
    }
}]

I want these to be converted to two nested backbone models with the following structure:

// structure
Image
    Layout
...

So I define the Layout model like so:

var Layout = Backbone.Model.extend({});

But which of the two (if any) techniques below should I use to define the Image model? A or B below?

A

var Image = Backbone.Model.extend({
    initialize: function() {
        this.set({ 'layout' : new Layout(this.get('layout')) })
    }
});

or, B

var Image = Backbone.Model.extend({
    initialize: function() {
        this.layout = new Layout( this.get('layout') );
    }
});

Source: (StackOverflow)

"Single-page" JS websites and SEO

There are a lot of cool tools for making powerful "single-page" JavaScript websites nowadays. In my opinion, this is done right by letting the server act as an API (and nothing more) and letting the client handle all of the HTML generation stuff. The problem with this "pattern" is the lack of search engine support. I can think of two solutions:

  1. When the user enters the website, let the server render the page exactly as the client would upon navigation. So if I go to http://example.com/my_path directly the server would render the same thing as the client would if I go to /my_path through pushState.
  2. Let the server provide a special website only for the search engine bots. If a normal user visits http://example.com/my_path the server should give him a JavaScript heavy version of the website. But if the Google bot visits, the server should give it some minimal HTML with the content I want Google to index.

The first solution is discussed further here. I have been working on a website doing this and it's not a very nice experience. It's not DRY and in my case I had to use two different template engines for the client and the server.

I think I have seen the second solution for some good ol' Flash websites. I like this approach much more than the first one and with the right tool on the server it could be done quite painlessly.

So what I'm really wondering is the following:

  • Can you think of any better solution?
  • What are the disadvantages with the second solution? If Google in some way finds out that I'm not serving the exact same content for the Google bot as a regular user, would I then be punished in the search results?

Source: (StackOverflow)

How to render and append sub-views in Backbone.js

I have a nested-View setup which can get somewhat deep in my application. There are a bunch of ways I could think of initializing, rendering and appending the sub-views, but I'm wondering what common practice is.

Here are a couple I've thought of:

initialize : function () {

    this.subView1 = new Subview({options});
    this.subView2 = new Subview({options});
},

render : function () {

    this.$el.html(this.template());

    this.subView1.setElement('.some-el').render();
    this.subView2.setElement('.some-el').render();
}

Pros: You don't have to worry about maintaining the right DOM order with appending. The views are initialized early on, so there isn't as much to do all at once in the render function.

Cons: You are forced to re-delegateEvents(), which might be costly? The parent view's render function is cluttered with all of the subview rendering that needs to happen? You don't have the ability to set the tagName of the elements, so the template needs to maintain the correct tagNames.

Another way:

initialize : function () {

},

render : function () {

    this.$el.empty();

    this.subView1 = new Subview({options});
    this.subView2 = new Subview({options});

    this.$el.append(this.subView1.render().el, this.subView2.render().el);
}

Pros: You don't have to re-delegate events. You don't need a template that just contains empty placeholders and your tagName's are back to being defined by the view.

Cons: You now have to make sure to append things in the right order. The parent view's render is still cluttered by the subview rendering.

With an onRender event:

initialize : function () {
    this.on('render', this.onRender);
    this.subView1 = new Subview({options});
    this.subView2 = new Subview({options});
},

render : function () {

    this.$el.html(this.template);

    //other stuff

    return this.trigger('render');
},

onRender : function () {

    this.subView1.setElement('.some-el').render();
    this.subView2.setElement('.some-el').render();
}

Pros: The subview logic is now separated from the view's render() method.

With an onRender event:

initialize : function () {
    this.on('render', this.onRender);
},

render : function () {

    this.$el.html(this.template);

    //other stuff

    return this.trigger('render');
},

onRender : function () {
    this.subView1 = new Subview();
    this.subView2 = new Subview();
    this.subView1.setElement('.some-el').render();
    this.subView2.setElement('.some-el').render();
}

I've kind of mix and matched a bunch of different practices across all of these examples (so sorry about that) but what are the ones that you would keep or add? and what would you not do?

Summary of practices:

  • Instantiate subviews in initialize or in render?
  • Perform all sub-view rendering logic in render or in onRender?
  • Use setElement or append/appendTo?

Source: (StackOverflow)

Loading Backbone and Underscore using RequireJS

I'm trying to load Backbone and Underscore (as well as jQuery) with RequireJS. With the latest versions of Backbone and Underscore, it seems kind of tricky. For one, Underscore automatically registers itself as a module, but Backbone assumes Underscore is available globally. I should also note that Backbone doesn't seem to register itself as a module which makes it kind of inconsistent with the other libs. This is the best main.js I could come up with that works:

require(
{
    paths: {
        'backbone': 'libs/backbone/backbone-require',
        'templates': '../templates'
    }
},
[
    // jQuery registers itself as a module.
    'http://cdnjs.cloudflare.com/ajax/libs/jquery/1.7/jquery.min.js',

    // Underscore registers itself as a module.
    'http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.2.1/underscore-min.js'
], function() {

    // These nested require() calls are just due to how Backbone is built.  Underscore basically says if require()
    // is available then it will automatically register an "underscore" module, but it won't register underscore
    // as a global "_".  However, Backbone expects Underscore to be a global variable.  To make this work, we require
    // the Underscore module after it's been defined from within Underscore and set it as a global variable for
    // Backbone's sake.  Hopefully Backbone will soon be able to use the Underscore module directly instead of
    // assuming it's global.
    require(['underscore'], function(_) {
        window._ = _;
    });

    require([
        'order!http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.5.3/backbone-min.js',
        'order!app'
    ], function(a, app) {
        app.initialize();
    })
});

I should mention that, while it works, the optimizer chokes on it. I receive the following:

Tracing dependencies for: main
js: "/home/httpd/aahardy/requirejs/r.js", line 7619: exception from uncaught JavaScript throw: Error: Error: Error evaluating module "undefined" at location "/home/httpd/aahardy/phoenix/trunk/ui/js/../../ui-build/js/underscore.js":
JavaException: java.io.FileNotFoundException: /home/httpd/aahardy/phoenix/trunk/ui/js/../../ui-build/js/underscore.js (No such file or directory)
fileName:/home/httpd/aahardy/phoenix/trunk/ui/js/../../ui-build/js/underscore.js
lineNumber: undefined
http://requirejs.org/docs/errors.html#defineerror
In module tree:
    main

Is there a better way of handling this? Thanks!


Source: (StackOverflow)

Angular.js Backbone.js or which has better performance

I am a web developer and I'm starting to develop a web application on a large scale, but I'm not sure what framework to use. I was thinking of Angular.js, but I also considered Backbone.js. For you, what would be the best framework? or at least have a comparison between the two to see the performance.


Source: (StackOverflow)

Backbone.js: get current route

Using Backbone, is it possible for me to get the name of the current route? I know how to bind to route change events, but I'd like to be able to determine the current route at other times, in between changes.


Source: (StackOverflow)

Backbone.js fetch with parameters

Following the documentation, I did:

var collection = new Backbone.Collection.extend({
        model: ItemModel,
        url: '/Items'
})

collection.fetch({ data: { page: 1} });

the url turned out to be: http://localhost:1273/Items?[object%20Object]

I was expecting something like http://localhost:1273/Items?page=1

So how do I pass params in the fetch method?


Source: (StackOverflow)

Angular.js vs Knockout.js vs Backbone.js [closed]

I am considering to use either Knockout or Angular or Backbone for my personal project. I need to build some bigger, longer-running client-side interactions to go with my server-side stuff.

I want a simple and effective way to manage data-driven user interfaces.

Which framework would you choose to solve my problem described above based on the feasibility as well as the performance aspect?


Source: (StackOverflow)

How to override Backbone.sync?

I'm trying out Backbone.js, and one of the things I'm trying is to make a call to a remote API, so I need to be able to override Backbone.sync, as I understand the documentation.

There isn't an example of how to do that in the documentation itself, and there doesn't appear to be a google group for Backbone... can someone point out an example for doing this?


Source: (StackOverflow)

How to use if statements in underscore.js templates?

I'm using the underscore.js templating function and have done a template like this:

<script type="text/template" id="gridItem">
    <div class="griditem <%= gridType %> <%= gridSize %>">
        <img src="<%= image %>" />
        <div class="content">
            <span class="subheading"><%= categoryName %></span>
            <% if (date) { %><span class="date"><%= date %></span><% }  %>
            <h2><%= title %></h2>
        </div>
    </div>
</script>

As you can see I have an if statement in there because all of my models won't have the date parameter. However this way of doing it gives me an error date is not defined. So, how can I do if statements within a template?


Source: (StackOverflow)