在knockout.js自定义绑定中不会调用更新

时间:2015-08-10 09:00:01

标签: knockout.js

以下是代码段

<!DOCTYPE html>

<html>
<body>

    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-min.js"></script>

    <div>
        <div data-bind="yourBindingName: someValue ">
        </div>
        <button data-bind="click: clickme">Click me!</button>
    </div>

    <script type="text/javascript">
        ko.bindingHandlers.yourBindingName = {
            init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
                console.log("init");
            },
            update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
                console.log("update");
            }
        };

        function ViewModel() {

            this.someValue = ko.observable('test');

            this.clickme = function () {
                console.log('clickme');
                this.someValue('');
            }
        }
        ko.applyBindings(new ViewModel());
    </script>

</body>
</html>

点击&#34;点击我!&#34;按钮只有&#39; clickme&#39;在控制台中,永远不会更新&#39;我希望每次更改绑定值时都会触发更新函数。

1 个答案:

答案 0 :(得分:3)

记录“更新”,但在您单击按钮之前。 Knockout已经运行过一次,并且在运行时检查了绑定处理程序使用哪些observable。由于您不访问其中的// Delegate method from the CLLocationManagerDelegate protocol. - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations { // If it's a relatively recent event, turn off updates to save power. CLLocation* location = [locations lastObject]; NSDate* eventDate = location.timestamp; NSTimeInterval howRecent = [eventDate timeIntervalSinceNow]; if (abs(howRecent) < 15.0) { // If the event is recent, do something with it. NSLog(@"latitude %+.6f, longitude %+.6f\n", location.coordinate.latitude, location.coordinate.longitude); } } (或其他任何内容),因此它知道在valueAccessor更改时不需要在绑定处理程序上调用update - 它将是一个浪费处理时间。如果您更新绑定处理程序以使用它,则会在someValue更改时调用它,即第一次单击按钮时:

someValue

这是一个演示:

ko.bindingHandlers.yourBindingName = {
    init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
        console.log("init: " + valueAccessor()());
    },
    update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
        console.log("update: " + valueAccessor()());
    }
};
ko.bindingHandlers.yourBindingName = {
    init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
        console.log("init: " + valueAccessor()());
    },
    update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
        console.log("update: " + valueAccessor()());
    }
};

function ViewModel() {
    
    this.someValue = ko.observable('test');
    
    this.clickme = function () {
        console.log('clickme');
        this.someValue('');
    }
}
ko.applyBindings(new ViewModel());