简体   繁体   中英

Emberjs serialize doesn't call model on {{linkTo}}

I have a route with the following format #/books/book/:bookId

When i am on the #/books and i click into the {{linkTo}}, then my model is not being executed and the following error is being returned.

Error while loading route: TypeError {} 
Uncaught TypeError: Object 4 has no method 'addArrayObserver' 

I know that a model is only being executed when you refresh the page with your browser, so i used the serialize, which according to the docs it should allow my model to be executed when i click into the {{linkTo}, but it doesn't. It returns the above error.

utils.get is an Ajax call which returns a json back... Could you tell me what i am doing wrong? Thank you.

App.Router.map(function() {
    this.resource("books", function() {
        this.resource("book", {path: "/book/:bookId"});
    });
});

var BookModel = Ember.Object.extend({});
BookModel.reopenClass({
    find: function(bookId) {
        var assets = Ember.A();
        utils.get('book/' + bookId, function(response) {
            response.assets.forEach(function(c) {
                assets.pushObject(BookModel.create(c));
            })
        });
        return assets;
    }
});


var BooksModel = Ember.Object.extend({});
BooksModel.reopenClass({
    findAll: function() {
        var books = Ember.A();
        utils.get('books', function(response) {
            response.books.forEach(function(c) {
                books.pushObject(BooksModel.create(c));
            })
        });
        return books;
    }
});

var BookRoute = Ember.Route.extend({
    model: function(params) {
        return BookModel.find(params.bookId);
    }

    ,serialize: function(model, params) {
        return { bookId: model };
    }
});


<h2>books</h2>
<ul class="nav nav-tabs nav-stacked">
    {{#each item in model}}
        <li>
            {{#linkTo "book" item.id}}{{item.name}}{{/linkTo}}
        </li>
    {{/each}}
</ul>
{{outlet}}

Basically every object (like your BookRoute ) needs to be under your App namespace for ember to be found:

App.BookRoute = Ember.Route.extend({
  ...
});

Also you should pass the model object to the linkTo helper:

{{#linkTo "book" item}}{{item.name}}{{/linkTo}}

and then in your serialize hook you then do:

serialize: function(model) {
    return { bookId: model.id };
}

Hope it helps.

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