Problem to pass object method as params?


#1

I have like this

var attr = {
   _id: '001',
   name: function(){
      return 'Theara';
   }
}

// I create factory to seed
Factory.define('post', Collection.Post, attr);

Factory.create('post');

I get error with name.
Please help me.


#2

name is a javascript reserved property. You can not use name as a method or property identifier, use something like firstName or fullName etc.

Here is the list of reserved words and properties.
http://www.w3schools.com/js/js_reserved.asp


#3

I change the name to other ...., but error (the field must be string).


#4

Without seeing your factory code, I can’t offer other suggestions.


#5
Factory = {};
Factory._factories = [];

var factoryFun = function (name, collection, attributes) {
    this.name = name;
    this.collection = collection;
    this.attributes = attributes;
};

Factory.define = function (name, collection, attributes) {
    var factory = new factoryFun(name, collection, attributes);

    for (var i = 0; i < this._factories.length; i++) {
        if (this._factories[i].name === name) {
            throw new Error('A factory named ' + name + ' already exists');
        }
    }

    Factory._factories.push(factory);
};

Factory._get = function (name) {
    var factory = _.findWhere(Factory._factories, {name: name});

    if (!factory) {
        throw new Error('Could not find the factory named ' + name);
    }

    return factory;
};

Factory.create = function (name, newAttr) {
    var factory = this._get(name);
    var collection = factory.collection;

    // Allow to overwrite the attribute definitions
    var attr = _.merge({}, factory.attributes, newAttr);

    var docId = collection.insert(attr);
    var doc = collection.findOne(docId);

    return doc;
};

Factory.build = function (name, newAttr) {
    var factory = this._get(name);

    var doc = _.merge({}, factory.attributes, newAttr);
    return doc;
};


#6

I copied the code you have supplied exactly and do not receive an error. Are the any other details you can provide such as packages used or where these code snippets are located e.g. client, server, both.


#7

I have problem if I define with object method

Factory.define('post', Collection.Post, {
   myName: function() {
      return 'Theara';
   }
});

It don’t allow to use object method.