2013-12-15 23 views
1

我評估Emberjs在我們是否可以將我們的一些代碼移植到它,但保持相同的API,所以我第一天真的看着它。在燼,如何得到一個參考模型在該控制器保存

我使用Tom Dale教程,但沒有使用ember-data。我想我已經想出瞭如何將數據導入應用程序(thx @ kingping2k)。我只需要得到這個保存/更新。

我有一個doneEditing動作,當我點擊它時被調用,如控制檯所見,但我如何獲得對模型的引用。看看控制器文檔(http://emberjs.com/api/classes/Ember.Controller.html),我沒有看到像model之類的非常明顯的屬性。我如何告訴PostController保存郵件回到其路由中?另外,人們通常使用jQuery承諾在保存完成後做些其他的事情(我假設是)?

我已經包含在底部的doneEditing行動在那裏我尋求幫助的相關代碼:當你從模型鉤子返回一個模型

THX任何幫助

Model: 
Hex.Post = Ember.Object.extend({ 
    id: null, 
    body: null, 
    isEnabled: null, 
    createdAt: null, 
    save: function(data){ 
     console.log("you want to save this item"); 
     $.post("api/post", data, function(data) { 
     // something here 
    }); 
    } 
}); 

View: 
<script type="text/x-handlebars" id="post"> 
    {{#if isEditing}} 
    {{partial 'post/edit'}} 
    <button {{action 'doneEditing'}}>Done</button> 
    {{else}} 
    <button {{action 'edit'}}>Edit</button> 
    {{/if}} 

    <h1>{{id}}</h1> 
    {{outlet}} 
</script> 

Route: 
Hex.PostRoute = Ember.Route.extend({ 
    model: function(params) { 
     console.log('called with: ' + params.post_id); 
     return Hex.Post.findById(params.post_id); 
    } 
}); 


Controller: 
Hex.PostController = Ember.ObjectController.extend({ 
    isEditing: false, 

    actions:{ 
    edit: function() { 
     this.set('isEditing', true); 
    }, 

    doneEditing: function() { 
     this.set('isEditing', false); 
     console.log("this gets called"); 
     //this.get('content').save(); 
     //this.save(); 
     //console.log("here: " + this.model.id); 
     //this.model.save(); //doesn't work ??? 
     // this.post.save(); //doesn't work ??? 
     //this.get('store').commit(); // prob no 
    } 
    } 
}); 

回答

2

然後傳遞給路由中的setupController。的setupController默認實現這樣做,controller.set('model', model)

setupController:function(controller, model){ 
    controller.set('model', model'); 
} 

因此得到控制的範圍內的模型只是得到該屬性。

var model = this.get('model') 

我會回來的承諾,那麼你就可以觸發保存/失敗等

save: function(){ 
    console.log("you want to save this item"); 
    return Ember.$.post("api/post", JSON.stringify(this)); 
} 

doneEditing: function() { 
    this.set('isEditing', false); 
    var model = this.get('model'); 
    model.save().then(function(){alert('saved');}, 
         function(){alert('failure');}); 
} 

的東西,通常你把保存在重新

Hex.Post.reopen({ 
    save: function(){ 
    console.log("you want to save this item"); 
    return Ember.$.post("api/post", JSON.stringify(this)); 
    } 
}); 
+0

THX @ kingping2k外觀很好,效果很好。你今天幫了我很多(週六不會少)。做得好;我真的很感激!我仍然會有更多的問題,雖然 – timpone

+0

保持他們的來臨,前幾天我剛剛做了肩袖手術,所以我被困在電視裏,看着電視和編程1手,這讓我保持理智。 – Kingpin2k

+0

抱歉聽​​到肩袖@ kingpin2k;希望你早日感覺好起來 - 現在,如果我可以讓websockets隨着這個... – timpone

相關問題