0

I have a model object defined like this

blog.js

define({title: '', url: '', summary: ''});

I'm using the blog model to hold data from a service and I need to populate an array of blogs. How do I instantiate a new blog within a loop in another module?

I've tried passing in blog as a require object, but it maintains it's reference inside the loop leaving an array of the same object over and over again.

othermodule.js

define(['blog'], function(blog) {
//... more code
  $.each(data, function(index, b) {
    var tmpBlog = blog;
    //...
    list.push(tmpBlog);
  });
});

I've also tried using var blog = require('blog'); yielding the same result.

So how do I instantiate the blog object using requirejs?

Jonas Stawski
  • 6,682
  • 6
  • 61
  • 106

1 Answers1

0

ok, I figured it out. I defined the blog model incorrectly. I needed to return a function blog(){...} instead like so:

define(function() {
  return function blog() {
    var self = this;
    this.title = '';
    //...
  };
});

and the other module used it like this:

define(['models/blog'], function (model) {
  var tmpBlog = new model();
  tmpBlog.title = 'some title';
}
Jonas Stawski
  • 6,682
  • 6
  • 61
  • 106
  • yes was just about to post that. [This question](http://stackoverflow.com/questions/4869530/requirejs-how-to-define-modules-that-contain-a-single-class) gives a lot more detail on the approach. – explunit Apr 25 '13 at 15:46