1

我即將從遠程檢索數據並創建模型和集合,這裏是應用程序(控制器,視圖和模型)的每個部分。 如果我真的明白在鈦中使用模型就像存儲到數據庫中一樣,即使在獲取所有數據後沒有互聯網連接,數據仍然存在。 下面的代碼運行良好,連接丟失後沒有顯示任何數據,所以我問自己,在鈦中使用模型而不是使用經典方式有什麼優勢:從xhr中檢索並顯示數據? 2-我的第二個問題(如果我錯了)檢索數據並存儲到模型後,我可以檢索它沒有xhr再次在另一個頁面內? 3-最後一個:從alloy.js中檢索數據並保存到模型是一種很好的做法,因爲我需要在所有應用程序頁面中使用數據?鈦加速器模型和集合持久性

控制器

// This is an istance of my xhr library 
 
var XHR = require('xhr'); 
 
var xhr = new XHR(); 
 

 
$.win.addEventListener('open', function(){ 
 
    
 
    url = 'mydomain.com/api/get_posts'; 
 
    xhr.get(url, onSuccess, onError); 
 

 
}); 
 

 
function onSuccess(response){ 
 
    
 
    if(typeof response !== null){ 
 
    datas = JSON.stringify(response.data); 
 
    postsModel = []; 
 
    _.each(datas, function(data){ 
 
     
 
    /* Create model */ 
 
    postsModel.push(Alloy.createModel('mypostsmodel',{ 
 
     title : data.title, 
 
     id : data.id 
 
    })); 
 
     
 
    }); 
 
    
 
    $.posts.reset(postsModel); 
 
    } 
 
}

** THE VIEW **

<Alloy> 
 
\t <Collection src="myposts" instance="true" id="myposts" /> 
 
\t <Window id="win" title="Inscription" class="container" > 
 
\t \t <View id="posts_view" class="myposts" dataCollection="$.myposts"> 
 
\t \t \t \t <View postId="{id}" class="post_item"> 
 
\t \t \t \t \t <Label class="post_label" text="{title}" /> 
 
\t \t \t \t \t <Label class="exp" id="exp_{id}" text="" /> 
 
\t \t \t \t </View> 
 
\t \t \t </View> 
 
\t \t </View> 
 
</Alloy>

THE MODEL

exports.definition = { 
 
\t config: { 
 
\t \t "columns": { 
 
      "title": "Text", 
 
      "id": "Integer" 
 
     }, 
 
     "defaults": { 
 
      "title": "-", 
 
      "id": "-" 
 
     }, 
 
\t \t adapter: { 
 
\t \t \t type: "sql", 
 
\t \t \t collection_name: "myposts" 
 
\t \t } 
 
\t }, 
 
\t extendModel: function(Model) {}, 
 
    ...

謝謝大家。

回答

0

我認爲在視圖中有更清晰的定義。在我看來,Alloy最大的貢獻就是能夠更清楚地將您的視圖與驅動應用程序的邏輯分開。你的邏輯也被簡化了(在大多數情況下!),因爲你需要做的只是將數據添加到集合中,並且Alloy處理顯示。

的替代品,你是如何做的:

_.each(datas, function(data){ 
var container = Ti.UI.createView({class: "post_item"}), 
    title = Ti.UI.createLabel({ 
    text: data.title, 
    class: "post_label" 
    }), 
    exp = Ti.UI.createLabel({class: "exp"}); 

    container.add(title); 
    container.add(exp); 
    $.posts_view.add(container); 
}); 

我已經做到了兩者兼得,甚至與合金,有時必須要做到這一點,因爲骨幹的侷限性,如實施鈦 - 但我想清楚如果你可以在標記中包含你的重複UI組件,它更容易閱讀和維護。

+0

嗨,感謝您的回覆,我真的很感謝,我只是想知道如何從我的代碼中堅持這些數據?謝謝。 – user44321