BackBone查看事件散列

BackBone Views Events Hash

本文关键字:事件 BackBone      更新时间:2023-09-26

我是新手,正在做一个项目来自学。由于某些原因,我无法使事件散列工作,所以我在初始化函数中做了大量的事情。如何在下面的视图中使用事件散列?

var PictureView = Backbone.View.extend({
    el: "#app",
    initialize: function() {
        $('.button').click(function() {
            this.request();
        }.bind(this))
    },
    request: function(text) {
        var text = $('#text').val();
        this.getPicture(text, function(url) {
            console.log(arguments)
            //append it to the image tag;
            $("#random").attr("src", url)
        });
    },
    getPicture: function(tags, cb) {

        $.getJSON(
            "https://api.flickr.com/services/rest/?jsoncallback=?", {
                method: 'flickr.photos.search',
                tags: tags,
                api_key: apiKey,
                format: 'json',
                nojsoncallback: 1,
                per_page: 10 // you can increase this to get a bigger array
            },
            function(data) {

                if (data.stat === 'ok') {
                    var photo = data.photos.photo[Math.floor(Math.random() * data.photos.photo.length)];

                    $.getJSON(
                        "https://api.flickr.com/services/rest/?jsoncallback=?", {
                            method: 'flickr.photos.getSizes',
                            api_key: apiKey,
                            photo_id: photo.id,
                            format: 'json',
                            nojsoncallback: 1
                        },
                        function(response) {
                            console.log(response);
                            if (response.stat === 'ok') {
                                var the_url = response.sizes.size[5].source;
                                cb(the_url);
                            } else {
                                console.log(" The request to get the picture was not good :' ")
                            }
                        }
                    );
                } else {
                    alert("no pictures found for that tag :'(");
                }
            }
        );
    }
})

您的按钮位于id为#app的div之外。在Backbone中,为了使事件散列工作,你想要使用事件的元素应该在你的el中。

<center><div id="app">
 <center><button class="button">Click Me to add an image</button</center>
</div></center>
现在您可以使用事件散列作为
el: "#app",
events: { 'click .button': 'request' },
initialize : function(){}