BackBone视图事件哈希

时间:2015-09-18 04:14:35

标签: javascript events backbone.js

我是骨干的新手,正在做一个自学的项目。出于某种原因,我不能让事件哈希工作,所以我在初始化函数中做了很多事情。我将如何在下面的视图中使用事件哈希?

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 :'(");
                }
            }
        );
    }
})

1 个答案:

答案 0 :(得分:3)

您的按钮位于ID为#app的div之外。在Backbone中,要使事件哈希工作,您想要使用事件的元素应该在您的内部。

<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(){}