Git Product home page Git Product logo

backbone's People

Contributors

akre54 avatar braddunbar avatar captbaritone avatar caseywebdev avatar craigmichaelmartin avatar gsamokovarov avatar hswolff avatar jashkenas avatar jdalton avatar jgonggrijp avatar jisaacks avatar joegermuska avatar jridgewell avatar knowtheory avatar krawaller avatar megawac avatar ogonkov avatar paulfalgout avatar pauluithol avatar philfreo avatar platinumazure avatar rymohr avatar sajibcse68 avatar samuelclay avatar sstephenson avatar tbranyen avatar tgriesser avatar thejefflarson avatar twobitfool avatar wyuenho avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

backbone's Issues

save only specific model attributes to the server

i have to "clean" my model before saving:

save: function(attributes, options) {
    // cleanup attributes before saving
    var that = this;
    var attrs = [
                 "id", "original_image_url", "original_image_file_name", "original_image_content_type", "modified_image_file_name", 
                 "modified_image_content_type", "original_image_file_size", "modified_image_file_size", "original_image_updated_at", 
                 "modified_image_updated_at", "created_at", "updated_at", "token"
    ];
    _.each(attrs, function(attr){ 
      that.unset(attr);
    });
    Backbone.Model.prototype.save.call(this, attributes, options);
}

would be nice to save only specific attributes:

  this.model.save({ page_number: 10 });

or

  this.model.save(['page_number', ...]);

Why Backbone.Model#toJSON is called on Backbone.Model#fetch?

I just realized that Backbone.Model#toJSON gets called on every Backbone.Model#fetch. It even gets called when when a corresponding Collection is fetched. Is this intensional? I'd expect toJSON to be called only on Backbone.Model#save. I'm using Backbone 0.0.3.

This causes problems in my case since my models (documents) aren't in a valid (serializable state) before they've been fetched and parsed.

In my scenario I'd like to load a document by just creating a new Document with an id property, then calling fetch.

loadDocument: function(id) {
  this.model = new Document({id: id});
  this.model.fetch({
    success: function() {
      // init doc
    }
  });
},

toJSON is unnecessarily (imo) called here, causing an error, because the document's ContentGraph (this.g) hasn't been setup properly.

toJSON: function() {  
  return _.extend(_.clone(this.attributes), {
    contents: this.g.serialize()
  });
},

My parse function looks like this:

parse: function(res) {
  if (res.contents) {
    this.g = new ContentGraph(res.contents);
  }
  return res;
},

Allow a mobile-friendly framework (Zepto) to be used in place of jQuery

Backbone is great for mobile webapp, but jQuery is not (large download by mobile platform standards, too large to be cached by Safari mobile as a matter of fact = real performance downer). Providing options to use the 2kb zepto.js as a replacement would be a real blessing for mobile web app developers in my humble opinion.

https://github.com/madrobby/zepto

note: I did some very basic testing substituting Zepto for jQuery before initializing backbone.js that seemed to work fine (...with a hack to create an a Zepto unbind() function which doesn't exist at the time of this writing) - see below for the hack:

<script type="text/javascript" src="/js/zepto.js"></script> <script type="text/javascript"> (function($){ $.fn['unbind'] = function(){ return $(this) } })(Zepto); this.jQuery = this.Zepto ; </script> <script type="text/javascript" src="/js/underscore-min.js"></script> <script type="text/javascript" src="/js/backbone-min.js"></script>

empty string attributes being reseted to null

Backbone.Model set function overwrites empty string attributes with null value, is there any reason for that?
Empty string in not the same as null...

backbone.js (v0.2.0) line 165:
if (val === '') val = null;

collection.fetch sends all models to the server

I noticed that if you have a collection with many models in it, when collection.fetch is run, it sends all of these models to the server as params--is there a reason for this? For large collections, the GET request gets very, very large.

Make the comparator method behave like Array.sort()

congrats to backbone.js, looks very promising.

One point of critism tough: the Backbone.Collection.Comparator method looks a bit weird to me. I would appreciate a comparator method defined in Backbone.Model that works like Javascript's array sort: it gets 2 model instances a and b for comparison and returns -1 if a > b, 0 if a == b or 1 if a < b.

This would allow more elaborate comparison functions that e.g. take multiple properties into account.

Collection Sorting + Updating View

I've just started playing with Backbone. Wondering what's the best approach for sorting and updating a view. I put together a little demo at http://backbone.line37.com/ but I'm sure there's a better way to do this:

alphaSort:function()
{
var alphabetical = Contacts.sortBy(function(contact) {
return contact.get("firstname").toLowerCase();
});

    $(".contact-list").html('');

    _.each(alphabetical, function(contact){ 
        App.addOne(contact);
    });

    return false;
}

Relations between models

How can I specify relations between models and query them? Take a simple tagging application as an example: you have one model representing your main entity (source code snippet, photo, comment etc) and one model representing a tag.

How can I query all main entities that have a certain tag assigned? Or all entities without tag?

this.template undefined

Hi,

I'm testing some of the docs examples in my browser but I always get "this.template undefined" when calling render() on a view.

var Bookmark = Backbone.View.extend({
  render: function() {
    $(this.el).html(this.template.render(this.model.toJSON()));
    return this;
  }
});

I thought that template should come from underscore.js?

'this' inside View.render() being set to the model?

I must be doing something wrong here. I'm trying to make a little demo to see what I can do with backbone, and basing it off your sample code. I an get "Uncaught TypeError: Cannot call method 'toJSON' of undefined". I see why it is doing this, because the bind("change", taskView.render) call is setting the context to the model (which the alert confirms), but it seems like there should at least be an argument to the render function to get access to the view. Maybe I am just going about it the wrong way? (see the sample code below).

Thanks,
Brian

<script type='text/javascript'>
var Task = Backbone.Model.extend({
    text: '',
    isFinished: false
});

var TaskView = Backbone.View.extend({
    tagName: 'li',
    className: 'task',
    render: function(model) {
        alert("does 'this' == model? " + (this == model));
        // Can't call render, because 'this' is not referencing the view
        $(this.el).html(this.template.render(this.model.toJSON()));
        return this;
    }
});


$(init);
function init() {

    var tasks = new Backbone.Collection;
    tasks.bind("add", function(task) {
        var taskView = new TaskView({
            model: task,
            id: 'task-' + task.cid
        });
        task.bind('change', taskView.render);
    });
    
    tasks.add([
      new Task({text: "Task 1"}),
      new Task({text: "Task 2"})
    ]);
    
    tasks.each(function(task) {
        task.set({ isFinished: false });
    });
}
</script>

Providing function for view id attribute

I'm attempting to construct an id from model attributes in a view by passing a function to the id attribute. After some debugging, I see that it assumes that the id and className will be static and not functions because the function executes in the context of the tag and so this isn't the view anymore.

I was thinking about updating the following code to optionally execute the properties if they are functions. Is this the best way to do this? If so, I'll submit a pull request.

_ensureElement : function() {
  if (this.el) return;
  var attrs = {};
  if (this.id) attrs.id = this.id;
  if (this.className) attrs.className = this.className;
  this.el = this.make(this.tagName, attrs);
}

Configurable id field name

some ORMs (mongoid for example) use _id instead of id. Would you accept a patch to support configurable id field name?

Shouldn't all business logic be in the Controller and only data in the Model?

I'm just trying to understand the thinking behind how the project has been structured? A part of me really likes it and seems to be exactly what I've been looking for but another part of me can't get over the fact that there doesn't seem to be a clean separation between the Model and Controller. Maybe this is valid in a JS framework, I'm not sure. Could you clarify you thought on this?
Thanks.

Cyclic history: when clicking backbutton, backbone.js cycles through last 2 states indefinitely

Using backbone 0.3.0, I have the following issue:

I create a controller and initialize:
new WorkspaceController();
Backbone.history.start();

When I click on hashlinks that match my routing pattern, things go well. However, when I use the backbutton on IE8 or Chrome dev, I cycle through the last 2 hashlinks. The behavior is as expected, not broken, on Firefox.

For example, say I have 3 links:
(1) #game/1
(2) #game/1/quest/1
(3) #scores/game/1

I click on 1, 2, then 3. This works, taking me where I need to go. I am now on #3. I click my backbutton, which takes me back to #2, as expected. I click back again. I would expect to go to #1, but instead I am taken back to #3. If I click back repeatedly, it cycles between #3 and #2 indefinitely on Chrome. On Firefox, the behavior is as expected (back to #2, then back to #1).

Better validation failure handling

Right now, when you save a model, the only way to display a validation error is to bind an error handler on the model object. This is inconvenient, to say the least. If I'm able to modify an instance of a model in two places on the page, with two views...I wouldn't want both views to show the error whenever an error occurs. Nor do I want to bind/unbind error handlers on the model object whenever I switch contexts between the two views.

In my local version of backbone.js, I've added a simple this.error = error just above the this.trigger('error', this, error); line. This allows me to do something like this
if(!my_model.save()){
alert(my_model.error);
}

Which, with the error binding way, would be rather difficult. Thoughts?

Backbone.sync by default looking for models property?

In the online documentation it says that by default REST styled API providers should return collections in a models property? Is this true? I couldn't find any supporting code in Backbone.js, rather it seems that Backbone by default expects an Array as the top level object returned from a fetch and sync for collections. Perhaps this was the case before the pass through parse method that can be overridden was added?

Is there a specific reason why filter/map/reject/etc don't return new Collections?

I would expect those methods to return new Collections, because generally when you map over something, you return a new type of that same something. For example, I would expect stillAlive to be a collection:

var coll = new MyCollection([foo, bar, baz, quux]);
var stillAlive = coll.filter(function (o) { return o.get("HP") > 0; });

Is this by design?

Aside: I really wish Github would make mailing lists or forums for projects, so that these types of issues wouldn't clog up the issues page...

empty string attributes being reseted to null

Backbone.Model set function overwrites empty string attributes with null value, is there any reason for that?
Empty string in not the same as null...

backbone.js (v0.2.0) line 165:
if (val === '') val = null;

API suggestions regarding fetching models. (Model.find)

Thanks for fixing Issue #77 that fast!

Just an idea regarding Model#fetch:

Why not adding a Model.get class method that takes an id and fetches the model right away.

Instead of writing:

this.model = new Document({id: id});
this.model.fetch({
  success: function() {
    // init doc
  }
});

One could write:

this.model = Document.get('doc-id', {
   success: function() {
     // init doc
   }
})

That being said, an Model.all class method could load a whole Collection of Documents in the same fashion.

var documents = Document.all({
  success: function() { ...}
});

What's your current strategy regarding the supply of query-params when fetching a Collection of items from the server, so that the server can deliver a reduced set of resources (according to the specified query-params)

I could imagine supplying them along with Model#all (Collection#fetch resp.):

var documents = Document.all({
  'author': 'john',
  'wordcount>=': 100 // greater than or equal to 100
}, {
  success: function() { ...}
});

I totally like the JSON based syntax of MQL (the query language used by freebase.com) http://wiki.freebase.com/images/e/e0/MQLcheatsheet-081208.pdf . Perhaps this could be a strategy to be used along with Backbone.js.

I'm not sure if this fits into the current design, though (esp. regarding the separation of Models and Collections). This is just an idea inspired by the API of DataMapper.

-- Michael

Updates to controller doc section.

Possibly make it clearer that Controllers and routing requires Backbone.history.start(). Focussing on trying that functionality, the docs didn't make it super clear.

Backbutton support in IE6?

Not sure if IE6 is supposed to be supported or not, but I find that the back button does not function as expected. As you click through various routed links that trigger onhashchange, they work fine, but pressing back doesn't iterate back through them. Instead, it goes back to the prior page ignoring any hashchange events. Example:

(0) Go to cnn.com, then go to your page that is using backbone.js. (1) Click, e.g., #job/1 (2) Click #job/2 (3) Click #job/3

Once you're on #job/3 and you press back, you'd expect to go to #job/2. Instead, on WinXP IE6 v 6.0.2600, you just get dumped back on CNN.com. Again, not sure if this is a supported browser or not, but thought I'd mention this.

When clicking backbutton in Win7 Chrome, backbone.js cycles through last 2 states indefinitely

(Recreating because I accidentally closed this the first time I created this...) I'm using backbone 0.3.0 with Chrome 9.0.576.0 dev with all extensions disabled on Win 7, and I have the following issue:

I create a controller with a couple of routes, and initialize like so:

new WorkspaceController();
Backbone.history.start();

When I click on hashlinks that match my routing pattern, things go well. However, when I use the back button on Chrome dev, I cycle through the last 2 hashlinks instead of going backwards normally.

For example, say I have 3 links:
(1) #game/1 (2) #game/1/quest/1 (3) #scores/game/1

I click on 1, 2, then 3. This works, taking me where I need to go. I am now on #3. I click my back button, which takes me back to #2, as expected. I click back again. I would expect to go to #1, but instead I am taken back to #3. If I click back repeatedly, it cycles between #3 and #2 indefinitely on Chrome. On Firefox, the behavior is as expected (back to #2, then back to #1).

Also, when the backbutton is pressed, the forward button is not enabled. It's as if this browser thinks that the action taken by the backbutton is a fresh, "new" event, not truly going backwards in its history but instead adding to it.

Of note, the Chrome+Win7 combo appears to be important, because the back button functionality works as expected on Chrome+XP that's running virtually.

Versions and Headers in Builds

  • Please include the version in the header comment in backbone.js.
  • Please preserve the header comment in backbone-min.js.

(I do see Backbone.VERSION = '0.2.0'; in the code. Is there a way also to include this in the header comment automatically?)

create separate modules for sync/network code and event/data binding code

I'd like to propose we break up the functionality of models and collections into modules for event handling and data binding and modules for network access and synchronization.

This would allows us to potentially make the data-binding capabilities of model available to all objects in the framework.

I think the following modules might make sense:

  • Backbone.Object - base object that includes the event binding capabilities in Backbone.Model
  • Backbone.Collection - includes the event binding and collection management capabilities of the current Bacbone.Collection
  • Backbone.Network - includes network synchronization and serialization code
  • Backbone.Model - composed of a Backbone.Object and Backbone.Network
  • Backbone.Store - composed of a Backbone.Collection and Backbone.Network

This would allow data-binding to become a lower level concept in the framework allowing us to potentially utilize it in views/controllers as well as models via including Backbone.Object.

Thoughts on this structure?

Single Page Web Applications (View Features)

I've recently been working on making a single-page web application (SPWA), and writing a js framework to do so... that is until I found backbone. I love the way it works, but it's just short of being able to do SPWA, as by default the views have no hide, or destroy, nor do they have the ability to have sub-views. Is this something that you'd be interested in backbone supporting? If so I'd be happy to do the brunt of it... maybe by creating an add-on module?

App specific base classes

This question/problem is probably due to my complete deficiency in Javascript skills, but hopefully you will know the answer :) I want to create a base Model, that sets up the conventions for my application, and then create individual models from that base that simply overrides where needed. If I do this:

app.view.MyBase = Backbone.Model.extend({ ..});

What I want to do is this:

app.view.NewModel = app.view.MyBase.extend({...});

But I get an error that .extend isn't a method on app.view.MyBase. Is there a simple way to achieve what I'm after? Thanks for your time.

Model validate() is not called properly

I was playing with the example called 'Todos' from the wiki and wanted to add a validate method to it. I added the following:
validate: function(att) { if(att.content.length < 4) { return "TOO SHORT TODO"; } }

But this did not work. The function would be called twice. Once with the expected object {content, order, done} but then once where the object had a simple key called proto containing a lot of garbage.

I can't seem to find any way to actually get the vaildate function to work.

I modified the Todos code minimanlly to add this validate method and we must assume that the example is coded correctly, so I can only assume that there is a bug in Backbone.js

Docs rendering suggestion

Picked up Backbone tonight and working on applying some basic concepts to an existing project.

This line of code appears twice in the docs, in particular inside the render method in the DocumentView example:

$(this.el).html(this.template.render(this.model.toJSON()));

My question is about the pattern used to achieve rendering. In DocumentView the example class doesn't implement a template attribute with a render method.

I made a couple assumptions and hacked together a working solution.
https://gist.github.com/1ac113d3cc2fef9fbe99

I created a TaskTemplate object literal with the variable html storing the ERB-style Underscore template. The render method receives attributes from the model and this particular template renders using Underscore's _.template method.

Is this similar to the the pattern that DocumentCloud uses?

Also, does all of your HTML exist inside of JS files or are they pulled from partials via Ruby?

With this pattern the HTML delivered to the browser would contain no markup for a task. Instead, it would delivery JSON or a JavaScript object which would render each element when the add event is triggered.

You mention bootstrapping the page in the docs. I'm wondering if that refers to rendering markup or generating JavaScript and delivering the model data with the HTML in a <script> tag or similar.

Is there a way to bind an element which pre-exists on the DOM? In an existing project, not using Backbone (yet), I render all the markup for existing objects and manipulate the model and corresponding views via event triggers.

Would be happy to publish a full sample app, once I get some clarity on "best-practice" patterns you've developed around this great library.

split source file

I think it could be interesting to split backbone source to have a separate file with each class. In case I vant to use only the view part or only the model part in my application. And why would I have to include sync if I will override it later? It is good to have a one file distribution, but for power users it is beter to have multiple files I think.

Why isn't this.handleEvents() called in Backbone.View.prototype.initialize?

Or even in the constructor or render? I can't think of a use case for when I wouldn't want to bind the event handlers on creation or render; I feel like I'm being forced to write little stubs that look like this all the time:

...
initialize: function () {
    this.handleEvents();
},
...

When I have nothing else to do in initialize.

Optional protoProps hash for subclasses?

I had the idea that protoProps should be an optional argument for a couple of reasons:

a) eliminates the resulting error if it's omitted
b) means that instanceof can be accurate for subclasses that exist to be descriptive only
c) more consistency, considering classProps is optional

I've studied the inheritance code and I can't see a reason why protoProps should have to be required to create a subclass (especially if it's just a conceptual one).

Anyone have any comments on this?

validation and datatypes of properties

One aspect I'm currently missing in backbone.js is an easy way to do property validation: declare required properties of a model and their datatypes, trigger an error if the data from the view doesn't pass the validation etc

Ability to circumvent the "models": [] namespacing requirement in Backbone.Collection.fetch

Hi!

While I like the idea to use models as a namespace, you sometimes will want to integrate against an existing JSON API that either uses another key, or a plain array. It would be nice to have the ability to somehow specify this with a property/function in the collection you're creating, e.g by declaring a responseKey property/function which is used to determine where in the response the model data is (much like the current url-property).

The only current solution is to monkey-patch the fetch-method (specifically the success-callback) itself, which isn't very pretty.

Example:

var c = Backbone.Collection.extend({
// ...
responseKey: "data"
// ...
});

var c2 = Backbone.Collection.extend({
responseKey: function(response){ return response; } // if it's just an array.
// you could also go deeper, eg response.data.documents
});

Should be a very simple fix to implement, so what do you guys think?

URL-handling enhancements when saving models

I have a collection and a model associated with it, and neither specify a url property. However, when I try to save the model, it uses the url property from the collection, which is undefined. So I get a URL resembling
PUT http://localhost:4567/undefined/1
or something, which...is not what I was expecting. Obviously the collection can't infer the name of itself, but I think Underscore.js should throw an error (or the docs should mention that the url property is required in order for the model to save correctly). Side note, and source of much of my confusion: the "- url" link under Collection actually links to Model#url, not Collection#url.

Summary:

  1. When saving a model, if any component of the generated url is "undefined", an error should be thrown
  2. Update docs to accurately characterize importance of Collection#url
  3. Update docs so that the "Collection - url" link in the left navigation points to Collection#url as one would expect.

Thanks!

Can't update model from within a change callback

I'm trying to figure out how to act on a changed select dropdown. My view renders multiple select controls and changing each one might trigger a change in subsequent ones (think "Country" -> "City" select sequence).

Problem is, according to "cautionary notes" in the docs, "change", "submit", and "reset" events do not bubble in current versions of Internet Explorer. Which means I can't use the view's event delegation, I suppose.

So, I tried attaching my change handler directly to the select element:

.change(function(e) { currentView.model.set({selectedAttribute: $(this).val()}); })

This doesn't work, because I end up in a render function that has "this" set to the model (?), not the view. The call stack is:

my view's render function (this is where I end up)
backbone.js:92
backbone.js:291
backbone.js:168
my .change() function

So it seems that changing the model triggers an immediate re-rendering of the view (which is fine), but I end up with this.model being undefined, because this points to my model.

I'm surely doing something wrong, but any pointers appreciated.

A simple example app would be very helpful

I realize this exposes my stupidity when it comes to client-side programming, but I'm having a bit of a hard time figuring out how to fit all these pieces together. I think that shipping a small example showing how one might put the pieces together would help quite a few people out.

For example, is it good practice to create a global instance of a Collection, and then have models reference that collection instance (seems bad)? Or is it better to pass that collection as a parameter to every model method (seems tedious)? What's the recommended way of kicking off the whole process and populating those initial collections?

I have a bunch of questions like this that seeing a simple example would probably quickly answer.

Idea - use JSON for the default POST and PUT sync

The current default implemenation of Backbone.sync uses a JQuery ajax call to POST and PUT objects as application/x-www-form-urlencoded in the body under a model param. This seems a bit hokey to me. Why not send it as JSON stringified without any parameter name? Isn't this how most REST styled JSON endpoints expect POST and PUT data? The JQuery ajax call will do this if the processData option is set to false, the contentType option is set to application/json and the body is set as JSON.stringified text. I can submit a pull request if there is agreement here. If not, no big deal as I can override Backbone.sync easily of course.

Allow loading route for empty fragment

I'd like to be able to load a route with an empty fragment. But the !current in checkurl prevents that.

routes: {
  "": "mydefaultroute", // this should be allowed
  "somefragment": "myotherroute",
},

Documentation update

On http://documentcloud.github.com/backbone/, the introduction begins:

"When working on a web application that involved a lot of JavaScript, one of the first things you learn "

That should be 'involves' rather than 'involved'.

Thanks for all your work, and the level of documentation is much appreciated!

this.el and existing elements

Even when I specify el, one still gets created, ie:

var MyView = Backbone.View.extend({
el: $('body'),

render : function() {
  alert(this.el);
}

});

myview = new MyView();
myview.render();

alert says "[object HTMLDivElement]" instead of the expected jQuery object. I think it has to do with the way views are instantiated, if I change Backbone.View to look if this.el is defined rather than this.options.el it works as expected.

Support JSON root node in request and response

Currently JSON does not support serializing model attributes within a root node. I believe this is default Rails 3 behavior for parsing incoming parameters and generating JSON.

I should have a patch for this soon.

What is the best way to model a Collection inside of a Model?

My team, is working with an interesting data schema. Basically what we have is a document that has a name and version and an array of items that belongs to it. The items themselves don't have ids associated with them because they belong to the larger model but the items can be added/edited/deleted from the main document. The model looks something like this:
{
name : "Test",
version : 1,
items : [
{name : "Item 1",
position : 0},
{name : "Item 2",
position : 1}]
}

It would be great to use a Collection for the underlying items in the Model but whenever the Collection gets updated, the Model should post back to the server with it's url. What is the best way to model this in Backbone? I'll be happy to post more in a gist if more info is needed.

Should models have direct access to views?

I'd like to see more separation between the application layers. From looking through the documentation it seems like models can directly access views and even insert content. The problem with this is that if you want to swap out view components you will also need to make changes to the model code. IMO models should know as little as possible about the rest of the system and changes should occur solely through events dispatched when data is changed.

P.S. I haven't had much chance to seriously investigate the framework so these thoughts are based on reading the documentation and my initial discoveries when creating a couple of extremely simple hello world apps. Very possible I'm just misunderstanding something...

Typo in docs

This question is frequently asked, and all three projects apply general Model-View-Controller principles to JavaScript applications. However, there isn't much basis for comparsion.

Besides that, looks like a great project!

Why no JSON posts with emulateHTTP?

I'm not sure why the change to have an emulateJSON (which was oddly named, but that is not the point) setting was removed. It seems to me that wanting to emulate http and wanting raw json posts are two separate needs. If I want JSON posts and emulate http, then why can't backbone just pass the X-Http-Method-Override header and be done with it?

I understand that some frameworks make it hard to get at raw post data, but I'm not sure why these two settings should be tied together.

Have Backbone.View call 'init' method if it exists?

Hi,
By adding this line:

this.init && this.init.apply(this);

to the end of the Backbone.View (http://github.com/documentcloud/backbone/blob/master/backbone.js#L496)

I am able to declare and run an init function on the template like this:

var TaskView = Backbone.View.extend({
    tagName: 'li',
    className: 'task',
    render: function() {        
        
        $(this.dom.text).text(this.model.get("text"));
        
        if (this.model.get("isFinished")) {
            $(this.dom.completeLink).hide();
            $(this.dom.incompleteLink).show();
        }
        else {
            $(this.dom.completeLink).show();
            $(this.dom.incompleteLink).hide();
        }
        
        
                return this;
    },
    init: function() {
        this.dom = {
            completeLink: this.make("a", {className: "complete", href:'#'}, "Complete"),
            incompleteLink: this.make("a", {className: "incomplete", href:'#'}, "Not Complete"),
            removeLink: this.make("a", {className: "remove", href:'#'}, "Remove"),
            text: this.make("span", {className: 'tasktext' })
        };
        
        $(this.el).
            append(this.dom.text).
            append(this.dom.completeLink).
            append(this.dom.incompleteLink).
            append(this.dom.removeLink);
            
        this.handleEvents();
    },
    
    events: {
        'click .complete': 'setFinished',
        'click .incomplete': 'setUnfinished',
        'click .remove': 'remove'
    },  
    setFinished: function() { 
        this.model.set({isFinished: true});
        return false;
    },
    setUnfinished: function() { 
        this.model.set({isFinished: false});
        return false;
    },
    remove: function() {
        return false;
    }
});

That way I don't need to have all the DOM creation in the render function (which could be called multiple times). I guess I could use a templating framework instead of this.make, but it would still be useful to have a function callback to have a place to run logic that only needs to run once. What do you think? Just an idea...

Brian

Segments of URL as History object property

I've been working with Backbone for an internal project and one thing I have found I often need is the segments of the URL as seen by the router. It's easy to do this, (assign the segments when a route gets executed), but it would be handy if this was processed automatically when the controller routes a request, and exposed through some global Backbone variable, (maybe in the history object)...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.