Search code examples
ember.jsnw.js

View doesn't update after pushing new POJO ember


I've always read that Ember works just fine with POJOs in place of Ember Data, but now that I'm giving it a shot, I'm having a little trouble.

I'm creating an app using NW.js and LinvoDB for the database. Fetching from the DB is easy and works great:

// route/index
import Ember from 'ember';

export default Ember.Route.extend({
    model: function() {
        var gui = require('nw.gui');
        var linvoDB = require('linvodb3');
        linvoDB.defaults.store = {db: require('medeadown')};
        linvoDB.dbPath = gui.App.dataPath;
        var File = new linvoDB('file', {} );
        var Tags = new linvoDB('tag', {});

        var media = new Promise(function(resolve, reject) {
            var query = File.find().sort({ctime: -1}).live();

            File.on('liveQueryUpdate', function() {
                resolve(query.res);
            });
        });

        var tags = new Promise(function(resolve, reject) {
            var query = Tags.find().sort({name: 1}).live();

            Tags.on('liveQueryUpdate', function() {
                resolve(query.res);
            });
        });

        return Ember.RSVP.hash({
            media: media,
            tags: tags
        });
    }
});

I have a simple event set up to create a tag, save it and push it into the model:

//controllers/index
actions: {
    viewMedia: function(media) {
        this.transitionToRoute('media', media)
    },
    addTag: function() {
        var linvoDB = require('linvodb3');
        var gui = require('nw.gui');
        linvoDB.defaults.store = {db: require('medeadown')};
        linvoDB.dbPath = gui.App.dataPath;

        var Tag = new linvoDB('tag', {});
        var tag = new Tag();
        tag.name = this.get('tagName');
        tag.save();
        this.get('model.tags').push(tag);
    }
}

I can verify that the tag object is being inserted correctly in the the tag array in the model, but the view isn't updating. From what I've read, that's cause I'm not using Ember.Object.

How are you suppose to do this with POJOs or do I have to use Ember.Objects? Thanks.


Solution

  • Ember provides it's own array implementation in Ember.Array/Ember.MutableArray that adds a lot of nifty things, like being properly observable in the Ember ecosystem. The Ember.MutableArray in particular (or rather Ember.MutableEnumerable if you want to go deep) has a method called pushObject(obj) that Push the object onto the end of the array. and also notifies any subscribers.

    Since Ember also is nice enough to add these to the regular Arrays prototype to make it easy for people to get going, you should be able to simply do this.get('model.tags').pushObject(tag); in your code.