简体   繁体   English

样式绑定中的Knockout.js图像

[英]Knockout.js image in Style binding

I've spent the last hour on this and I know it's going to be something small... I'm trying to embed a background image for a model using a computable (or observable, I feel like I've tried every way) and it either tells me "is not defined" or doesn't compute the value at all. 我已经花了最后一个小时了,我知道这会很小...我正在尝试使用可计算的(或可观察的,我觉得我已经尝试了所有方法)为模型嵌入背景图片它要么告诉我“未定义”,要么根本不计算值。 My latest failed attempts and the errors. 我最近的失败尝试和错误。

View(haml) 查看(HAML)

no Error, but doesn't render 无错误,但不渲染

.columns.large-10.background{"data-bind" => "with: currentEvent, style: { backgroundImage}"}  

error: image is not defined 错误:未定义图片

.columns.large-10.background{"data-bind" => "with: currentEvent, style: { backgroundImage: 'url(' + image() + ')' }"}    

Model 模型

    function Item(data) {
        this.name = ko.observable(data.name);
        this.isDone = ko.observable(data.isDone);
    }

    function Event(data) {
        var self = this;
        self.name = ko.observable(new EditableText(data.name, false));
        self.description = ko.observable(new EditableText(data.description, false));
        self.date = ko.observable(new EditableText(data.date, false));
        self.location = ko.observable(new EditableText(data.location, false));
        self.state = ko.observable(new EditableText(data.state, false));
        self.city = ko.observable(new EditableText(data.city, false));
        self.zip = ko.observable(new EditableText(data.zip, false));
        self.allow_guest_create = ko.observable(new EditableText(data.allow_guest_create, false));
        self.host_name = ko.observable(new EditableText(data.host_name, false));
        self.street_address = ko.observable(new EditableText(data.street_address, false));
        self.start_time = ko.observable(new EditableText(data.start_time, false));
        self.end_time = ko.observable(new EditableText(data.end_time, false));
        self.event_type = ko.observable(new EditableText(data.event_type, false));
        self.image = ko.observable(data.image);
        self.backgroundImage = ko.computed(function() {
            return { "backgroundImage": 'url('+self.image+')' };
        }, self);
        self.bgImageUrlStyle = ko.computed(function() {
            return "url(" + self.image() + ")";
        });
        self.edit = function (model) {
            console.log(model.text())
            model.editing(true);
        };
    }

    function EditableText(text, editable) {
        var self = this;
        self.text = ko.observable(text);
        self.editing = ko.observable(false);
    }


    function MasterVM() {
        var self = this;    
        self.newItemName = ko.observable();
        self.items = ko.observableArray([]);
        self.events = ko.observableArray([]);

        self.currentEvent = ko.observable();

        self.addEvent = function(data) { self.events.push(new Event(data));};

        self.removeEvent = function(event) { self.events.remove(event) }

        self.addItem = function() {
            self.items.push(new Item({ name: self.newItemName() }));
            self.newItemName("");
        };

        self.removeItem = function(item) { self.items.destroy(item);};

        self.save = function(data) {
            console.log(ko.toJSON({ event: self }))
            $.ajax("/events", {
                data: ko.toJSON({ event: self }),
                type: "post", contentType: "application/json",
                success: function(result) { console.log(result) }
            });
        }

        self.getEvent = function(data) {
            $.ajax("/events/", {
                data: { id: 50 },
                type: "get", contentType: "application/json",
                success: function(result) { 
                    console.log(result)
                    self.currentEvent(new Event(result));
                }
            });
        }

        self.getEvent();
    }

The problem is that your with binding is on the same element as the style binding. 问题是您的with绑定与style绑定位于同一元素上。

But the with only applies to its children so you need to write currentEvent(). 但是with仅适用于其子项,因此您需要编写currentEvent(). in your style binding to access the properties of your event object: 在样式绑定中访问事件对象的属性:

.columns.large-10.background{"data-bind" => "with: currentEvent, 
    style: currentEvent() && currentEvent().backgroundImage"} 

But in this case you need to handle the case when currentEvent() is null and you will have problems with the encoding of & ( How could I escape a & in Haml so that it compiles to & instead of &? (Haml noob) ) 但是在这种情况下,您需要处理currentEvent()为null的情况,并且&的编码会出现问题( 我如何在Haml中转义&以便将其编译为&而不是&amp ;?(Haml noob)

A more proper solution would be to move the with binding outside to your div with using the containerless syntax 一种更合适的解决方案是使用无容器语法将with绑定移到div外部

/ ko with: currentEvent
.columns.large-10.background{"data-bind" => "style: backgroundImage"}
/ /ko  

Sidenote: you are missing a () in your backgroundImage computed after self.image: 旁注:您缺少在self.image之后计算出的backgroundImage()

self.backgroundImage = ko.computed(function() {
        return { "backgroundImage": 'url(' + self.image() + ')' };
}, self);

Demo JSFiddle . 演示JSFiddle

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

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