繁体   English   中英

钛,合金在两个窗口中使用模型的实例

[英]Titanium, Alloy use instance of a model in two windows

我正在使用钛合金,我想做这样的事情:

我有一个模型,视图和控制器,这是视图index.xml-

<Alloy>
<Model src="post" instance="true" id="postIns"/>
<Window class="container" onSwipe="update" model="$.postIns">
    <Label id="postTitle" top="15">{$.postIns.title}</Label>
    <Label id="postContent">{$.postIns.body}</Label>
    <Button id="updateButton" onClick="update" bottom="0">Zemi nov post</Button>
</Window>

这是模型-post.js-

exports.definition = {
config: {
    "defaults": {   
        "userId": "",
        "id": "",
        "title": "Title",
        "body": "",
    },

    adapter: {
        type: "properties",
        collection_name: "post"
    }
},
extendModel: function(Model) {
    _.extend(Model.prototype, {
        // extended functions and properties go here
    });

    return Model;
},
extendCollection: function(Collection) {
    _.extend(Collection.prototype, {
        // extended functions and properties go here
    });

    return Collection;
}

};

和连接到假api并填充模型实例的控制器index.js-

var id = 1;

function update() {

    id =_.random(0, 50);

    var results = {};

    var client = Ti.Network.createHTTPClient({    
    //  called when the response data is available    
    onload : function(e) {        
        results = JSON.parse(client.responseText);        
        // display results on console        
        Ti.API.info(JSON.stringify(results,null,2));  
        // save the results to the instance
        $.postIns.save(results);  
        },    
        //  called when an error occurs, including a timeout    
    onerror : function(e) {        
        results = JSON.parse(client.responseText);        
        // display error results on the console        
        //Ti.API.err(JSON.stringify(results,null,2));    
        },
});

    var url = "http://jsonplaceholder.typicode.com/posts/" + id;

    client.open("GET", url);

    client.send();
}

$.index.open();

现在假设我想用另一个窗口创建另一个视图文件.xml,我将如何在该窗口中使用相同的post模型实例? PS:我很确定我制作的模型实例是本地的,但是我对将模型绑定到更多窗口的解决方案感兴趣。

您可以查看钛合金文档,该文档清楚地说明了模型的全局单例实例,我认为您将可以使用它。 看看Titanium doc单词:

您还可以在标记或控制器中创建模型的全局单例实例,可以在所有控制器中访问该实例。 将Alloy.Models.instance方法与模型文件的名称一起使用,将扩展名减去扩展名作为创建或访问单例的唯一参数。

// This will create a singleton if it has not been previously created,
// or retrieves the singleton if it already exists.
var book = Alloy.Models.instance('book');

希望它能提供一些想法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM