【问题标题】:Is there a better way to access durandal current view from subscribtion callback?有没有更好的方法从订阅回调访问 durandal 当前视图?
【发布时间】:2014-09-24 23:13:32
【问题描述】:

为了确保我正在访问当前视图,我可以这样做:

function attached(view, parent) {
    $("#element",view).hide();
}

这将返回一个undefined

viewModel.selectedcategory.subscribe(function (data,view) {
    console.log(data,view);
    $("#element",view).hide();
});

所以我访问视图的方法是,我定义了一个全局变量currentView,如下所示:

var currentView,

viewModel = {
   activate: activate,
   attached: attached,
   selectedcategory: ko.observable(false)
}

viewModel.selectedcategory.subscribe(function (callback) {
    console.log(callback, activeView);// now i can access the view 
    $("#element",activeView).hide();
});
return viewModel;

function attached(view, parent) {
    currentView = view; // update currentView
    $("#element",view).hide();
}

有没有更好的方法来像订阅一样做同样的事情

viewModel.selectedcategory.subscribe(function (subscribeView, subscribeParent) {


});

【问题讨论】:

    标签: knockout.js durandal


    【解决方案1】:

    无需以您的方式引用“当前视图”——本质上,您正在缓存它。

    在您的 attached 处理程序中,执行以下操作:

    var $view = $(view);
    

    然后,继续在该函数中使用 $view。

    如果您倾向于缓存视图,那么您的代码还不够模块化。例如,缓存视图的常见重构是创建自定义 Knockout 绑定。在您的情况下,您可以为 hide() 创建一个简单的自定义 Knockout 绑定,您可以将其称为 toggle()

    ko.bindingHandlers.toggle = {        
        update: function(element, valueAccessor) {
            // Initially set the element to be instantly visible/hidden depending on the value
            var value = valueAccessor();
            $(element).css('visibility', ko.unwrap(value));           
        }
    };
    

    使用这个绑定很简单(我从我的代码中提取了这个):

    <div class="ts-message__datetime">
        <div class="ts-data--readonly" data-bind="toggle: showMessageDates(), text: messageBo().created(), css: cssClassSpeechBubbleDates()"></div>
    </div>
    

    所以,现在,不是缓存视图以便您可以显示/隐藏,而是在 viewModel 上创建一个可观察对象(在我上面的例子中,我有一个名为 showMessageDates 的可观察对象,默认为隐藏):

    var showMessageDates = ko.observable(false);
    

    在您的 viewModel 中,只要您希望影响元素的显示/隐藏状态,只需更改 observable 的值即可。

    为了更明确地回答您的问题,是的,有一种比订阅更好的方法:自定义 Knockout 绑定!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-01
      • 1970-01-01
      • 2017-12-19
      • 1970-01-01
      • 1970-01-01
      • 2014-08-15
      • 2012-06-02
      相关资源
      最近更新 更多