简体   繁体   English

从匿名函数访问 Vue 方法

[英]Accessing Vue methods from anonymous function

I'm just having a play with Vue.js (pretty new to javascript too) and trying to access the events in my Google calendar.我只是在玩 Vue.js(对 javascript 也很陌生)并尝试访问我的 Google 日历中的事件。

I keep getting 'undefined' when looking in the console.在控制台中查看时,我一直在“未定义”。

    new Vue({
    el: '#app',
    data: {
        client_id: 'my_client_id',
        scopes: ["https://www.googleapis.com/auth/calendar.readonly"],
        events: {
            title: 'Upcoming Events',
            items: [],
        }
    },
    created: function () {
        this.loadCalendarApi();
    },
    methods: {
        addEvent: function (event) {
            this.events.items.push({
                title: event.summary,
                date: event.start.dateTime
            });
        },
        loadCalendarApi: function () {
            gapi.client.load('calendar', 'v3', this.listUpcomingEvents);
        },
        listUpcomingEvents: function () {
            var request = gapi.client.calendar.events.list({
                'calendarId': 'primary',
                'timeMin': (new Date()).toISOString(),
                'showDeleted': false,
                'singleEvents': true,
                'maxResults': 10,
                'orderBy': 'startTime'
            });
            var events = this.requestEvents(request);
            console.log(events);
        },
        requestEvents: function (request) {
            return request.execute(function (resp) {
                resp.items;
            });
        },
    },
});

I think the offending code is somewhere in the requestEvents method.我认为有问题的代码在 requestEvents 方法中的某个地方。

I also know that 'this.addEvent' is not in scope to be able to refer to the Vue object from inside the request.execute function but I don't know what I need to change.我也知道 'this.addEvent' 不在能够从 request.execute 函数内部引用 Vue 对象的范围内,但我不知道我需要更改什么。

Can anyone help me or let me know what I'm doing wrong?谁能帮助我或让我知道我做错了什么?

Thanks!谢谢!

Two ways you could do it, one would be to change execute(function) to execute(function, vue) and pass this in as the second argument.有两种方法可以做到这一点,一种是将execute(function)更改为execute(function, vue)并将this作为第二个参数传递。 Then you could access it like so:然后你可以像这样访问它:

//update your execute function to pass along the vue variable into the response, then

requestEvents: function (request) {
        var events = request.execute(function (resp, vue) {
            for (i = 0; i < resp.items.length; i++) {
                vue.addEvent(resp.items[i]);
            }
        }, this);
        return events;
    }

Or if you have jQuery available, you can take a look at $.proxy() which alters a function to use the current context: https://api.jquery.com/jQuery.proxy/或者如果你有可用的 jQuery,你可以看看$.proxy()改变一个函数来使用当前上下文: https ://api.jquery.com/jQuery.proxy/

requestEvents: function (request) {
        var events = request.execute($.proxy(function (resp) {
            for (i = 0; i < resp.items.length; i++) {
                this.addEvent(resp.items[i]);
            }
        }, this));
        return events;
    }

This way the anonymous response function will be run in the context of your Vue object.这样匿名响应函数将在 Vue 对象的上下文中运行。

Edit: I found this page as well which shows how you can bind the current context to a function using native JS, jQuery, or Underscore.编辑:我也找到了这个页面,它展示了如何使用原生 JS、jQuery 或 Underscore 将当前上下文绑定到一个函数。 Any of these would work: https://jsperf.com/bind-vs-jquery-proxy/5这些中的任何一个都可以工作: https ://jsperf.com/bind-vs-jquery-proxy/5

Nowadays you could use the request => {} notation instead of function(request) {} notation, which will pass on the context to the executing method so this.AddEvent() will work as expected.现在您可以使用 request => {} 表示法而不是 function(request) {} 表示法,它将上下文传递给执行方法,因此 this.AddEvent() 将按预期工作。

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

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