Pushing to properties in Backbone [duplicate] - javascript

This question already has an answer here:
Backbone View extends is polluted
(1 answer)
Closed 8 years ago.
I spent a lot of time trying to catch a bug in my app. Eventually I set apart this piece of code which behavior seems very strange to me.
var Model = Backbone.Model.extend({
myProperty: []
});
var one = new Model();
var two = new Model();
one.myProperty.push(1);
console.log(two.myProperty); //1!!
What's the reason behind it? Why it acts so? How to avoid this type of bugs in code?

Inheritance in JavaScript is prototypical - objects can refer directly to properties higher up in the prototype chain.
In your example, one and two both share a common prototype, and do not provide their own values for myProperty so they both refer directly to Model.protoype.myProperty.
You should create new myProperty array for each model you instantiate. Model.initialize is the idiomatic place for this kind of initialisation - overriding constructor is unnecessarily complex.
var Model = Backbone.Model.extend({
initialize: function() {
this.myProperty = [];
}
});
Alternatively you could make myProperty as an attribute of the model:
var Model = Backbone.Model.extend({
defaults: function() {
return {
myProperty: []
}
}
});
It is important to note that defaults is a function - if you were to use a simple object you would encounter the same shared reference issue.

Actually its because myProperty is an array, and as you know arrays will be stored by reference. Just to test consider the following code:
var Model = Backbone.Model.extend({
myProperty: [],
messege: ''
});
var one = new Model();
var two = new Model();
one.messege = 'One!';
two.messege = 'Two!';
console.log(one.messege ); // 'One!'
console.log(two.messege ); // 'Two!'
An alternative around this could be:
var Model = Backbone.Model.extend({
constructor: function() {
this.myProperty = [];
Backbone.Model.apply(this);
}
});
var one = new Model();
one.myProperty.push(1);
var two = new Model();
console.log(two.myProperty); // []

The documentation says:
constructor / initialize new Model([attributes], [options])
When creating an instance of a model, you can pass in the initial values of the attributes, which will be set on the model. If you define an initialize function, it will be invoked when the model is created.
In rare cases, if you're looking to get fancy, you may want to override constructor, which allows you to replace the actual constructor function for your model.
So, following the documentation, you'd want to do something like this to get your case running:
var Model = Backbone.Model.extend({
initialize: function() {
this.myProperty = [];
}
});
source: http://backbonejs.org/#Model-extend

Related

How can we create an instance of Backbone view using the string name store in a javascript object?

I'm creating a visual builder using different view for each component. All the view are declared like below:
$(function() {
var parallaxView = new Backbone.view.extend({
....
});
var parallaxView = new Backbone.view.extend({
....
});
});
At one point i start to create a new object view from that view. But all i know is the string represent the name of the view store in an object
name
My question can we create an object in some way such as new class using that object value as class name.
var myView = new name(param1, param2);
instead of using
switch (name) {
case 1:
....
}
I have try this case
var myView = new name(param1, param2);
and i know that it won't wok. But is there any way to can create an object in someway like that?
If I understand your question in a right way, you can store views constructors in object like this:
$(function() {
window.views = {
'parallax': Backbone.View.extend({ /*...*/ }),
'test': Backbone.View.extend({ /*...*/ })
};
});
Then you can create instances this way:
// var name = 'parallax';
var myView = new window.views[name](param1, param2);
Please let me know if your problem is not like I understand it.

Backbone: annoying behaviour of prototype object

I understand this is a problem (or behaviour) of javascript itself rather than Backbone's extend method, but I'd like to know what is the best strategy to avoid it.
Let's better put it in code:
var MyModel = Backbone.Model.extend({
value: 0,
values: []
});
var myFirstModel = new MyModel();
myFirstModel.value // 0, as expected
myFirstModel.values // [], as expected
var mySecondModel = new MyModel();
mySecondModel.value = 2;
mySecondModel.values.push(2)
mySecondModel.value // 2, as expected
mySecondModel.values // [2], as expected
myFirstModel.value // 0, as expected
myFirstModel.values // [2], ... WAT!!!
I do understand that the problem is I'm not assigning a new value to mySecondModel.values I'm just operating on the values variable that is in the prototype, that is MyModel.prototype.values (same problem with any other object, of course)
But it's very easy to mess with that. The most intuitive thing is to just think of those as INSTANCE variables, and not variables common to every instance (static or class variables in class based languages).
So far now the general solution I've found is to initialize every variable in the initialize method, like this:
var MyModel = Backbone.Model.extend({
initialize: function() {
this.value = 0;
this.values = [];
}
});
That way everything works as expected, and even though it wouldn't be neccesary for a simple value (like this.value) I find it much easier to just stick to this prnciple in every case.
I'm wondering if there's some better (more elegant, clearer) solution to this problem
This is an effect of JavaScript's prototypical inheritance and the fact that Array objects are reference types. The key/value pairs of the object you pass to extend are copied onto the prototype of MyModel, so they will be shared by all instances of MyModel. Because values is an array, when you modify it, you modify the array for every instance.
What you are doing by setting values inside initialize is called shadowing the prototype, and it is the correct way to solve this issue.
That said, in the case of Backbone.Model, if you are attempting to deal with the model's attributes, you can use the defaults function to provide defaults like this:
var MyModel = Backbone.Model.extend({
defaults: function() {
return {
value: 0,
values: []
}
}
});
Again, this is only for attributes of an instance.
var inst = new MyModel();
// The defaults will be created for each new model,
// so this will always return a new array.
var values = inst.get('values');
For what you are doing, where you are specifying properties on the model itself, it is up to you to set the defaults inside of initialize, as you have done.
Are you intentionally not setting value and values as backbone attributes? If you set attributes on an instance, instead of putting them in the extended backbone model definition, it might work how you expect.
var MyModel = Backbone.Model.extend();
var myFirstModel = new MyModel({
value: 0,
values: []
});
console.log(myFirstModel.get('value'); // 0
console.log(myFirstModel.get('values'); // []
var mySecondModel = new MyModel({
value: 2,
values: [2]
});
//mySecondModel.value = 2;
//mySecondModel.values.push(2)
console.log(mySecondModel.get('value'); // 2
console.log(mySecondModel.get('values'); // [2]
console.log(myFirstModel.get('value'); // 0
console.log(myFirstModel.get('values'); // []
jsFiddle, check the console log.
I too had stumbled across this problem some time back and solved it by defining a defaults method in the model.
var MyModel = Backbone.Model.extend({
defaults: function() {
return {
value: 0,
values: []
}
}
});

Preventing multiple instances of a constructor function from sharing the same prototype properties

Right when I thought I had a hold on how prototypal inheritance works in JavaScript, I run into an issue I hadn't before considered.
Take a look at the following simple JavaScript code:
var Observable = function () {
this.events = [];
};
Observable.prototype.addEvent = function (e) {
this.events.push(e);
};
var Model = function () {};
Model.prototype = new Observable();
var appModel = new Model();
var taskModel = new Model();
appModel.addEvent('Hello');
taskModel.addEvent('World');
Looking at either appModel.events or taskModel.events yields the same array: ['Hello', 'World']. What I am looking to do is have each new Model have its own events array in as clean a fashion as possible. The following implementation of Model works:
var Model = function () {
this.events = [];
};
Model.prototype = new Observable();
However, as more properties are added to Observable this becomes more unwieldy. I thought I could fix this as follows:
var Model = function () {
this.prototype.constructor.apply(this, arguments);
};
Model.prototype = new Observable();
Alhtough as I'm sure those of you who are more experienced in JavaScript realize this throws an error: TypeError: Cannot read property 'constructor' of undefined.
In summary I am looking for a way for each new Model to inherit properties from Observable and for each Model to have its own events. I realize that this is very class-like, but I would like to know how to do this using only JavaScript prototype-based inheritance.
It is worth noting that I have looked at Dean Edward's Base.js. The following works:
var Observable = Base.extend({
constructor: function () {
this.events = [];
},
addEvent: function (e) {
this.events.push(e);
}
});
var Model = Observable.extend({
constructor: function () {
this.base();
}
});
var appModel = new Model();
var taskModel = new Model();
appModel.addEvent('Hello');
taskModel.addEvent('World');
But the following doesn't:
var Observable = Base.extend({
events: [],
addEvent: function (e) {
this.events.push(e);
}
});
var Model = Observable.extend({
constructor: function () {
this.base();
}
});
var appModel = new Model();
var taskModel = new Model();
appModel.addEvent('Hello');
taskModel.addEvent('World');
Besides the point, I would like to learn how to do this with JavaScript prototypes using no class libraries.
What I have understood here is that you want each instance to have their separate events array, If so follow the answer:
function Model(){
this.events = [];
this.addEvent = function(eventName){
this.events.push(eventName);
};
this.getEvents = function(){
return this.events;
}
}
var m1 = new Model;
var m2 = new Model;
m1.addEvent("eve-1");
m2.addEvent("eve-2");
m1.getEvents(); //["eve-1"]
m2.getEvents(); //["eve-2"]
In your case you are adding events directly to the prototype not the instances hence they are added across all the instances...I hope this should help
I had tried this to fix my problem:
var Model = function () {
this.prototype.constructor.apply(this, arguments);
};
Model.prototype = new Observable();
The actual solution is to do this:
var Model = function () {
Model.prototype.constructor.apply(this, arguments);
};
Model.prototype = new Observable();
This will give each Model its own events array as well as give each Model any other properties that the Observable constructor creates. The small overhead here is that Model.prototype.events is an empty array that is never accessed.
The reason why your first bit of code there causes each instance of Model to have a common events array is because they have a prototypical reference to a single common instance of Observable. In other words, by doing
Model.prototype = new Observable();
You are basically telling JavaScript "make all instances of Model act like this specific instance of Observable".
There are a couple of different ways to correctly perform prototypical inheritance in JavaScript. If you can get by with the recently standardized ECMAScript 6, you can use the handy new class and extends keywords designed for this very purpose.
class Observable {
constructor() {
this.events = [];
}
addEvent() {
this.events.push(e);
}
}
class Model extends Observable {
// Model definition
};
Unfortunately support for ECMAScript 6 still isn't great. ECMAScript 5 added Object.create which has been the preferred method of doing inheritance since (at least as far as I'm aware).
var Observable = function () {
this.events = [];
};
Observable.prototype.addEvent = function (e) {
this.events.push(e);
};
var Model = function () {
Observable.call(this);
};
Model.prototype = Object.create(Observable.prototype);
MDN has a pretty nice article on OOP in JavaScript using this technique.

Backbone: Id not being set to model

I have tried the following to set an id to my model:
var globalCounter = 1;
var Model = Backbone.Model.extend({
initialize: function () {
this.id = globalCounter;
globalCounter += 1;
}
});
myModel = new Model();
console.log(myMode.get('id')); // prints undefined
How can I set an id to my models?
You need to use the set() function instead (http://jsbin.com/agosub/1/);
var globalCounter = 1;
var Model = Backbone.Model.extend({
initialize: function () {
this.set('id', globalCounter);
globalCounter += 1;
}
});
myModel = new Model();
console.log(myModel.get('id')); // prints 1
You must use :
this.set('id', globalCounter);
instead of this.id = globalCounter;
You are adding the id value to the Model object, but you want to add it to Model.attributes object. And that what is doing Model.set() method.
model.set("key", value) will put the value in model.attributes.key;
model.get("key") will return the value inside model.attributes.key
This is a little weird for new comers to Backbone, but it's a major (and easy) point to get. It's designed so that using model.set(...) will fire change events you can easily catch to update your views.
Backbone and ES6 Update :
The Backbone attribute object is outdates by ES6 getters and setters. Theses functions can overwrite the standard access.
Warning : this is pseudo-code that may be one day used with ES6 !
class MyModel extends Backbone.Model{
get id(){ return this.attributes.id; }
set id(id){ this.attributes.id = id; }
}
This would allow to write :
let myModel = new Model();
myModel.id = 13; // will use myModel.id(13)
console.log (myModel.id); // will show myModel.id()
As of today, this is only a dream of a Backbone 2. After basic searches, I've seen nothing about that coming.

Adding more functions to Backbone Models

I am attempting to add some functions to backbone so that I can communicate with mongodb. Now I know this won't work client side; however, I do like backbone's functionality for server side model logic as well. I noticed that I would be doing a bunch of repeat work if I kept adding the same functionality for each model so decided to create a "app_model" file to extend backbone when I'm server side. I also don't want to override the standard Backbone functions because they will be useful client side.
So let's take this user class for instance:
var Backbone = require('./app_model');
var User = Backbone.Model.extend({
name : "users",
defaults: function() {
return {
username: "default",
role: 2,
created: new Date(),
updated: new Date(),
logged: new Date()
};
},
idAttribute: "username",
/**
* A predefined listing of user roles
*/
userRoles: [
"admin", //0
"author", //1
"user" //2
],
initialize: function() {
if(!!app) {
this.svrInit();
}
}
});
module.exports = User;
And I want to append functions onto backbone by using my "app_model.js" file, which looks something like this currently:
var Backbone = require('backbone'),
Deferred = require('Deferred'),
when = Deferred.when;
Backbone.Model.prototype.svrInit = function() {
//TODO: perhaps the code below should be made static some how so we don't have a bunch of instances of collection
var model = this;
if(!!app.db){
app.db.collection(this.name,function(err,collection){
model.collection = collection;
});
}
};
Backbone.Model.prototype.svrSave = function() {
var model = this.toJSON();
var dfd = new Deferred();
this.collection.insert(model, {safe:true}, function(err, result){
dfd.resolve();
});
return dfd;
};
Backbone.Model.prototype.svrFind = function(options) {
var model = this.toJSON();
var dfd = new Deferred();
this.collection.find(options, {safe:true}, function(err, result){
dfd.resolve();
});
return dfd;
};
module.exports = Backbone;
I ran my tests when I abstracted this out and it seemed to work alright. Is there a better way to do any of this? Any pit falls? I am using the global "app" variable, is that bad? If so what are some ways around it? I do find it ugly that I had to put this.svrInit() inside the init function at the model level is there anyway to automatically make that happen after creation?
So I've been thinking about this question for a couple days and I the cleanest thing I've come up with is something like this:
var MyModel = function( attributes, options ) {
Backbone.Model.apply( this, arguments );
this.specialInitializer();
};
MyModel.extend = Backbone.Model.extend;
_.extend( MyModel.prototype, Backbone.Model.prototype, {
specialInitializer: function() {
// called after the users 'initialize'
console.log("MyModel initialized.", this);
},
otherNewMethod: function() {
// this is just like any other instance method,
// just as if Backbone.Model implemented it
}
} );
So what this does is basically make an entirely new 'kind' of Backbone.Model. One which also calls specialInitializer. If you look at the backbone source just after the constructor definition for Backbone.Model you'll see this is a similar strategy.
Construct the instance.
Call an initializer the implementor is supposed to define.
Extend the prototype with functionality (in their case Backbone.Events, in ours, Backbone.Model).
Your new initializer can of course call whatever else it needs, etc.
As for your other questions about the static collection stuff and global app variable, I'm afraid I don't follow exactly what is going on there since I don't see a definition for app and don't know what you're using the collection for.
Here's a fiddle that demonstrates this with some extra logging and such.
I'm working on a fairly large code-base with 4-5 levels of inheritance in the views. This is the pattern I'm using:
var BaseView = Backbone.Model.extend({
somefunc: function() {
//contents
},
otherfunc: function(a,b,c) {
//contents
},
//...
});
var User = BaseView.extend({
// things in user view can now access somefunc and otherfunc
});
Here's a quick example in a jsfiddle (note the doSearch function being inherited)

Categories

Resources