65.9K
CodeProject 正在变化。 阅读更多。
Home

在 #titanium #alloy #TiDev 上使用依赖注入

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0投票)

2014年9月21日

MIT

1分钟阅读

viewsIcon

7244

在 #titanium #alloy #TiDev 上使用依赖注入

我看到一些文章说,在任何地方都使用 Ti.App.fireEvent 不是一个好的做法。解决方案是使用 $.trigger 组件方法。这没问题。全局事件是邪恶的!

我认为真正的问题不是全局事件是好是坏。对我来说,真正的问题是

如何创建一个可维护的 Titanium 应用?

Alloy 控制器

当你创建一个 Alloy 组件(js + tss + xml)时,编译过程会生成类似这样的代码:

function Controller() {
    require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
    this.__controllerPath = "index";
    arguments[0] ? arguments[0]["__parentSymbol"] : null;
    arguments[0] ? arguments[0]["$model"] : null;
    arguments[0] ? arguments[0]["__itemTemplate"] : null;
    var $ = this;
    var exports = {};
    $.__views.index = Ti.UI.createWindow({
        backgroundColor: "white",
        id: "index"
    });
    $.__views.index && $.addTopLevelView($.__views.index);
    $.__views.label = Ti.UI.createLabel({
        width: Ti.UI.SIZE,
        height: Ti.UI.SIZE,
        color: "#000",
        text: "Hello, World",
        id: "label"
    });
    $.__views.index.add($.__views.label);
    exports.destroy = function() {};
    _.extend($, $.__views);

    ////// HERE goes your controller code

    _.extend($, exports);
}

var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;

module.exports = Controller;

生成的代码存在以下问题:

  1. widget.js 不是一个 CommonJS 模块,它只是附加到编译代码中的一堆代码。
  2. 没有控制器实例的概念(你的代码将被附加到控制器函数)。
  3. 由于 2),我们无法轻松地测试我们的组件,因为它依赖于生成的结构。
  4. 由于 2),我们无法管理控制器实例及其依赖项,而无需使用全局变量(如果人们对全局事件说坏话,那么全局变量也是邪恶的。)
  5. ... 告诉我还有什么其他问题!

Alloy 中的依赖注入

依赖注入是一个非常熟悉的的概念,用于降低大型应用程序的复杂性。其中一些优点是:

  • 实例生命周期/注册 作为声明式编程
  • 实例创建 使用工厂模式(由 IOC 容器提供)
  • 实例依赖项(声明式编程)

为了说明我的观点,我创建了一个使用依赖注入的原型。这在你的业务层和 UI 之间创建了一个分离。

https://github.com/aetheon/ti-app-dependency-injection-example

我真的很想知道你的想法。如果能从 titanium 团队获得一些反馈,那将是太棒了。

请与你的 Titanium 开发同伴分享这篇文章。

奥斯卡结束!

© . All rights reserved.