简体   繁体   中英

Ember.js 'Objects' and 'ArrayController'

I'm getting my feet wet with a bit of Ember.js. I'm trying to create a super simple form that lets you submit a query.

App = Ember.Application.create();

App.QueryFormView = Ember.View.extend({
    submitQuery: function () {
        App.queries.pushObject({
            firstName: this.get('name'),
            message: this.get('message')
        });

        App.queries.save();
    }
});

// Model
App.Query = Ember.Object.extend();

// Collection
App.queries = Ember.ArrayController.create({
    content: [],
    save: function () {
        $.post('api/query', JSON.stringify(this.toArray()), function (data) {
            // Queries saved
        });
    }
});

Each time the query form it submitted, I push an object to the queries ArrayController , and then run save.

However, I'm struggling to understand where the Ember.Object aka model comes into play. It's not being used at all here, and I'd like to know how to properly utilise it.

You don't have to use Ember.Object . If you never want to do any bindings, have calculated properties or observe any property changes, there's no need.

However if you do want to do any of those things you'd modify your code like this:

Document expected fields in the model.

// Model
App.Query = Ember.Object.extend({
  firstName: null, // just to indicate what props you're expecting
  lastName: null
});

Create your model object instead of anonymous object.

submitQuery: function () {
    App.queries.pushObject(App.Query.create({   // .create() here
        firstName: this.get('name'),
        message: this.get('message')
    });

    App.queries.save();
}

And now for the big drawback. JSON.stringify() will serialize internal stuff you don't want. So each object sent over the wire must be simplified to the properties you want first. Help with this can be found here: Reflection on EmberJS objects? How to find a list of property keys without knowing the keys in advance

save: function () {

    var obj = buildSimpleObject(this); // implements this somehow

    $.post('api/query', JSON.stringify(obj.toArray()), function (data) {
        // Queries saved
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM