我正在尝试以某种方式将以下模型的属性绑定(bind)到 Controller ,以便在模型完成其异步调用时设置模型的长度属性,然后通知 Controller 更改并可以更新看法。
App.Articles = Ember.Object.extend()
App.Articles.reopenClass
store: {}
lengths: 0
findAll: ->
arr = Ember.ArrayProxy.create()
$.ajax
url: 'http://ajaxcall.asp',
dataType: 'json'
context: @
success: (response) ->
Ember.set(App.Articles, 'lengths', response.store.length)
response.store.forEach (news, i) =>
txt = '<p>' + news.fields[2].text.replace(/[\r\n]+(?=[^\r\n])/g,'</p><p>') + '</p>'
article =
'id': i
'date': news.fields[1].date
'title': news.fields[0].text
'text': txt
'short': news.fields[2].text.substring(0, 120) + '...'
art = @findOne(article.id)
art.setProperties(article)
return
values = (values for keys, values of @store)
arr.set('content', values)
callback = ->
$('.loader-container').removeClass('show')
$('#articles-scroll').css('height', $(window).height() - 55)
articles_scroll = new iScroll 'articles-scroll',
vScroll: true, hScroll: false, vScrollbar: false
return
setTimeout callback, 100
return
arr
findOne: (id) ->
art = @store[id]
if not art
art = App.Currencies.create
id: id
@store[id] = art
art
所以我需要完成的是设置调用完成后返回的数据的长度,并在 Controller 中监听该变化,如下所示:
lengths: (->
console.log 'test'
).property('App.Articles.lengths')
但是,我对上面的代码并不走运,我不确定如何解决这个问题。
最佳答案
如果您想在模板中使用该值,只需使用 Controller 的长度属性:{{controller.length}}
。
如果你想观察 Controller 中的长度属性:
App.ArticlesController = Ember.ArrayController.extend({
lengthDidChange: function() {
console.log("Length changed to: " + this.get('length'));
}.observes('length')
});
假设您在路由的 model
Hook 或其他地方使用 articles 数组设置 Controller 。
更新:
如果您想要一次性通知,请将 Ember.Evented
混合到您从 findAll
返回的 ArrayProxy
中(省略不需要的内容):
App.Articles.reopenClass
...
findAll: ->
arr = Ember.ArrayProxy.createWithMixins(Ember.Evented)
$.ajax
...
success: (response) ->
...
arr.set('content', values)
arr.trigger('didLoad')
App.ArticlesRoute = Ember.Route.extend
model: ->
App.Articles.findAll()
setupController: (controller, model)->
model.one 'didLoad', ->
console.log controller.get('lastObject`)
关于javascript - Ember.js - 如何将模型类的属性绑定(bind)到 Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15950470/