2

enter image description here

recently, i came across a question of how jQuery acts as both a function, as well as an object. the thing that made it possible was that jQuery was actually a function (hence the $()) that was attached with properties (like $.each()).

now in my project, i would want to create a model (which technically is an array of stuff), add methods to it, and return it to a variable which will hold it. is it wise to do it like this? does it interfere with anything?

//i did it like this:
function createModel(name){
    var model = internal.models[name] = [];
    model.add = function(){..logic to add to the model..}

    //more augmented methods here...

    return model;
}

//create a model
var myModel = createModel('test');

//then i can do add
myModel.add('foo');

To add to that, I don't want to mess around with the actual Array prototype stuff. I'm doing this for the currently created array.


the model i'm making is not like Backbone.js' model which is a unit of data. It's more synonymous to Backbone.js' Collection, or a Database table.

Community
  • 1
  • 1
Joseph
  • 117,725
  • 30
  • 181
  • 234

1 Answers1

1

Something in that style might do, also never start a model as an array, always take a function (constructor) and a proper object they are more flexible for that.

var model = function(data) {
    this.data = data;
};

model.prototype.getData = function() {
    return this.data;
};

var mod = new model({foo:'foo'});

mod.getData().foo
GillesC
  • 10,647
  • 3
  • 40
  • 55
  • updated my post. actually, the code is in a function that returns the newly created model for reference, as well as manipulations. – Joseph Apr 13 '12 at 12:44