I have static properties that I would like to access from instances of my Backbone.Model objects. I know I could hardcode the parent constructor to call the method, but this prevents me from having polymorphic static functions. For example, I would like to be able to override the foo
function in ExtendedInventory
if necessary, without having to change any other code.
var Inventory = Backbone.Model.extend({},
//STATIC
{
foo: function() {
alert('bar');
}
});
var i = new Inventory({});
i.constructor.foo(); //This works!
var ExtendedInventory = Inventory.extend({});
var ei = new ExtendedInventory({});
ei.constructor.foo(); //THIS DOES NOT WORK
//How do I generically access the `Inventory.foo()` function via the `ei` object. I would
js Get model is used to get the value of an attribute on a model. Syntax: model. get(attribute)
You can use the Backbone. Model without jQuery, but Backbone. View will require either jQuery or Zepto, just like the docs state. Chances of not using view and router is low enough.
Backbone.js is a small JavaScript library for organizing developers' JavaScript code. Backbone.js library is a single JavaScript file with less than 1,000 lines of JavaScript code (not including the code comments). This means Backbone.js is lightweight and easy to integrate into JavaScript-heavy applications.
Backbone is known for being lightweight, as its only hard dependency is on one JavaScript library, Underscore. js, plus jQuery for use of the full library. It is designed for developing single-page web applications, and for keeping various parts of web applications (e.g. multiple clients and the server) synchronized.
Hmm. Though the code above does work, I wouldn't leave it that way. If the function is logically accessible through an object of the class, then define an instance method in the base class that calls the class/"static" function. This makes the code cleaner and clearer, I think (plus, clients don't have to remember the somewhat arcane syntax):
var Inventory = Backbone.Model.extend({
foo: function() {
this.constructor.foo();
}
}, {
foo: function() {
alert('bar');
}
});
var i = new Inventory({});
i.foo(); //This works!
var ExtendedInventory = Inventory.extend({});
var ei = new ExtendedInventory({});
ei.foo();
What doesn't work exactly, in your example? In both Firefox and IE, I get two popups with 'bar', which looks like the intended result? The static part of it appears to behave fine as well, see this jsfiddle.
(this is with the HEAD version of Backbone, btw; don't know if that makes a difference)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With