Laracast Video(Push Events to the Client) error? - laravel

I try to create event handling...so i followed this video tutorial ..everything working perfect. but in last minute video when i try to show user name in list view its not updating in real time as list view but i checked console.log('users') each object i can get it from my console.... but in view no updates or no errors ......... what is error ?
This is video tutorial - LINK
<body>
<ul id="users">
<li v-repeat="user: users">#{{ user.name }}</li>
</ul>
<script src="https://js.pusher.com/3.0/pusher.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.20/vue.min.js"></script>
<script>
// (function () {
// var pusher = new Pusher('82355e6cc93e7a15d7d5', {
// encrypted: true
// });
//
// var channel = pusher.subscribe('test');
// channel.bind('App\\Events\\UserHasRegistered', function(data) {
// console.log(data);
// });
// })();
new Vue({
el: '#users',
data:{
users:[]
},
ready: function(){
var pusher = new Pusher('82355e6cc93e7a15d7d5', {
encrypted: true
});
pusher.subscribe('test')
.bind('App\\Events\\UserHasRegistered',this.addUser);
},
methods: {
addUser: function(user){
this.users.push(user);
}
}
})
</script>
</body>

The v-repeat directive is deprecated in version 1.0 and replaced with the v-for.
1.0 replaces the old v-repeat directive with v-for. In addition to providing the same functionality and more intuitive scoping, v-for provides up to 100% initial render performance boost when rendering large lists and tables!
http://vuejs.org/2015/10/26/1.0.0-release/#Faster-Initial-Rendering

Related

vue 2 v-for not working after loading json with axios

I searched the internet for a solution but none did work so far.
I am having a Vue component where I want to load dropdown content afterwards. Since it does not work, I simplified the code such that it should only show me the elements (which are driver names).
The problem is, that the v-for seems not to work, as the elements are not created in the DOM.
Here goes the code:
<template>
<div class="list-group">
<a class="list-group-item" v-for="driver in drivers">
{{driver.name}}
</a>
</div>
</template>
<script>
export default {
name: "DriverComponent",
data: function (){
return {
drivers: [],
}
},
mounted(){
this.loadDrivers();
console.log(this.drivers);
},
methods: {
loadDrivers: function(){
axios.get('/api/drivers')
.then(
(response) => {
this.drivers = response.data.data;
console.log(this.drivers);
}
)
.catch(function(error){
console.log(error);
});
// console.log(this.drivers);
}
}
}
</script>
In my app.js:
require('./bootstrap');
window.Vue = require('vue').default;
Vue.component('driver-component', require('./components/DriverComponent.vue').default);
const drivers = new Vue({
el: '#driv',
});
And my html looks as follows:
<div id="driv">
<driver-component></driver-component>
</div>
As you can see, I added some logs, which look like this:
Image of console output
Interestingly, it should be the same array, but the first array is empty but the second has the right values in it.-> EDIT: clarified, thank you
to highlight the problem: i would expect a list like:
v-for created list
Instead, I get a blank page.
It works, if I initialize the drivers array with the data I get in json. However, since I load the data afterwards, it seems not to work
Thank you for your help!
BR
Johannes
EDIT:
I am using "axios": "^0.21" and the controller is:
public function index(){
return DriverResource::collection(Drivers::all());
}
this controller returns the array in a data field, therefore, I set the response.data.data (meaning two times data)
The backend returns:
{"data":[{"id":1,"name":"UPS"},{"id":2,"name":"Hermes"}]}
See the homepage for axios. Under the "Response Schema" section they provide what a response looks like. Specifically for data, it's
{
// `data` is the response that was provided by the server
data: {}
< ... omitted for brevity ... >
}
Please check again what your backend is returning or is supposed to return. Log the whole response you get.
The this.drivers = response.data.data; seems to be incorrect, however the this.drivers = response.data; should work.
You didn't say which version of axios you are using or show your configuration so I'm using the following for an example:
axios = ^0.21.1
vue-axios = ^3.2.4
Replaced "name" with "title" to match the response format below:
{
"title": "delectus aut autem",
< ... omitted for brevity ... >
},
--
loadDrivers: function(){
Vue.axios.get('https://jsonplaceholder.typicode.com/todos')
.then(
(response) => {
this.drivers = response.data; // <<-- works and many task titles are shown on page
// this.drivers = response.data.data; // <<-- DOES NOT WORK LIKE FOR YOU, blank page
console.log(this.drivers);
}
)
.catch(function(error){
console.log(error);
});
// console.log(this.drivers);
}

Unknown custom element: - did you register the component correctly?

I'm new to vue.js so I know this is a repeated issue but cannot sort this out.
the project works but I cannot add a new component. Nutrition component works, profile does not
My main.js
import Nutrition from './components/nutrition/Nutrition.vue'
import Profile from './components/profile/Profile.vue'
var Vue = require('vue');
var NProgress = require('nprogress');
var _ = require('lodash');
// Plugins
Vue.use(require('vuedraggable'));
// Components
Vue.component('nutrition', Nutrition);
Vue.component('profile', Profile);
// Partials
Vue.partial('payment-fields', require('./components/forms/PaymentFields.html'));
// Filters
Vue.filter('round', function(value, places) {
return _.round(value, places);
});
Vue.filter('format', require('./filters/format.js'))
// Transitions
Vue.transition('slide', {enterClass: 'slideInDown', leaveClass: 'slideOutUp', type: 'animation'})
// Send csrf token
Vue.http.options.headers['X-CSRF-TOKEN'] = Laravel.csrfToken;
// Main Vue instance
new Vue({
el: '#app',
components: {
},
events: {
progress(progress) {
if (progress === 'start') {
NProgress.start();
} else if (progress === 'done') {
NProgress.done();
} else {
NProgress.set(progress);
}
},
'flash.success': function (message) {
this.$refs.flash.showMessage(message, 'success');
},
'flash.error': function (message) {
this.$refs.flash.showMessage(message, 'error');
}
}
});
Profile.vue
<template>
<div class="reddit-list">
<h3>Profile </h3>
<ul>
</ul>
</div>
</template>
<script type="text/babel">
export default {
name: 'profile', // this is what the Warning is talking about.
components: {
},
props: {
model: Array,
}
}
</script>
profile.blade.php
#extends('layouts.app')
#section('title', 'Profile')
#section('body-class', 'profile show')
#section('content')
<script>
window.Laravel.profileData = []
</script>
<profile></profile>
#endsection
Whenever I try to go to this page I get:
[Vue warn]: Unknown custom element: <profile> - did you register the component correctly? For recursive components, make sure to provide the "name" option.
I tried doing a local component such as
Vue.components('profile', {
template: '<div>A custom component!</div>'
});
or even I tried adding the profile into the components in vue but still no luck, can anyone point me in the right direction?
Simply clear the cache on your browser if you run into this problem. Worked pretty well for me
I didn't fixed it but it was fixed by itself it appears some kind of magic called (CACHE). i did have my gulp watch running but i powered off my computer, and then ON again and it works.

Instagram API with more than 20 images

I wanted to ask you, if there is any possibility to get more than 20 full-res images from Instagram, using the API.
<script type="text/javascript">
var feed = new Instafeed({
get: 'user',
userId: '2201292293',
clientId: 'MY_CLIENT_ID',
accessToken:`'MY_ACCESS_TOKEN',
limit: '364',
sortBy: 'most-liked',
template: '<img src="{{image}}">{{likes}}',
resolution: 'standard_resolution'
});
feed.run();
Thank you in advance, Laurenz Strauch
It may be caused by pagination.
Add
<button id="load-more">
Load more
</button>
to your html. Every time you click on the button, feed.next() will be called and fetches more images if they exist.
<script type="text/javascript">
var loadButton = document.getElementById('load-more');
var feed = new Instafeed({
get: 'user',
userId: '2201292293',
clientId: 'MY_CLIENT_ID',
accessToken:`'MY_ACCESS_TOKEN',
limit: '364',
sortBy: 'most-liked',
template: '<img src="{{image}}">{{likes}}',
resolution: 'standard_resolution'
// every time we load more, run this function
after: function() {
// disable button if no more results to load
if (!this.hasNext()) {
loadButton.setAttribute('disabled', 'disabled');
}
},
});
// bind the load more button
loadButton.addEventListener('click', function() {
feed.next();
});
// run our feed!
feed.run();
</script>
Try this code.

canjs component tempate dom live binding

My code is to realize a paginate page like this example, https://github.com/bitovi/canjs/blob/master/component/examples/paginate.html .
I found the {#messages}...{/messages} in message.mustache template was not been inserted into page , while messagelist component inserted event has been triggered, so i can not do any binding to {#messages} dom in the event, because it ‘not exists in the page.
Are there other ways to fix this problem?
The Templates:
message_list.mustache:
<app>
<messagelist deferredData='messagesDeferred'></messagelist>
<next-prev paginate='paginate'></next-prev>
<page-count page='paginate.page' count='paginate.pageCount'></page-count>
</app>
message.mustache:
{#messages}}
<dl>
<dt>.....</dt>
<dd>....</dd>
</dl>
{/messages}
The Component:
can.Component.extend({
tag: "messagelist",
template: can.view('/static/web/tpl/mobile/message.mustache'), // to load message template
scope: {
messages: [],
waiting: true,
},
events: {
init: function () {
this.update();
},
"{scope} deferreddata": "update",
update: function () {
var deferred = this.scope.attr('deferreddata'),
scope = this.scope,
el = this.element;
if (can.isDeferred(deferred)) {
this.scope.attr("waiting", true);
deferred.then(function (messages) {
scope.attr('messages').replace(messages);
});
} else {
scope.attr('messages').attr(deferred, true);
}
},
"{messages} change": function () {
this.scope.attr("waiting", false);
},
inserted: function(){
// can't operate the dom in message.mustache template
}
}
});
//to load component template
can.view("/static/web/tpl/mobile/message_list.mustache",{}, function(content){
$("#message-list").html(content)
});
I have solved the problem, but not the best, Maybe someone have a better way.
I changed my template, add a new component called <messageitem>
<messageitem> will load another template: message.mustache
Every <messageitem> will trigger inserted event when inserted into <messagelist>
The new component:
can.Component.extend({
tag: "messageitem",
template:can.view('/static/web/tpl/mobile/message.mustache'),
events: {
inserted: function(el, ev){
// Can-click can not satisfy my needs,
// because i call the third-party module to bind click event
// this module will be called repeatedly, not the best way
reloadModules(['accordion']);
}
}
});
// To load message_list.mustache
can.view("/static/web/tpl/mobile/message_list.mustache",{}, function(content){
$("#message-list").html(content)});
Static html:
<body>
<div id="message-list">
....
</div>
</body>
message_list.mustache:
<app>
<messagelist deferredData='messagesDeferred'>
{{#messages}}
<messageitem></messageitem>
{{/messages}}
</messagelist>
<next-prev paginate='paginate'></next-prev>
<page-count page='paginate.page' count='paginate.pageCount'></page-count>
</app>
message.mustache:
<dl class="am-accordion-item" >
...
</dl>

AngularJS update View after Model loaded from Ajax

I'm newbie of angularjs developing and i wrote this simple app, but don't understand how i can update view, after the model il loaded from ajax request on startup!
This code don't work when I add delay into photos.php, using:
sleep(3);
for simulate remote server delay! instead if search.php is speedy it work!!
<!doctype html>
<html ng-app="photoApp">
<head>
<title>Photo Gallery</title>
</head>
<body>
<div ng-view></div>
<script src="../angular.min.js"></script>
<script>
'use strict';
var photos = []; //model
var photoAppModule = angular.module('photoApp', []);
photoAppModule.config(function($routeProvider) {
$routeProvider.when('/photos', {
templateUrl: 'photo-list.html',
controller: 'listCtrl' });
$routeProvider.otherwise({redirectTo: '/photos'});
})
.run(function($http) {
$http.get('photos.php')//load model with delay
.success(function(json) {
photos = json; ///THE PROBLEM HERE!! if photos.php is slow DON'T update the view!
});
})
.controller('listCtrl', function($scope) {
$scope.photos = photos;
});
</script>
</body>
</html>
output of photos.php
[{"file": "cat.jpg", "description": "my cat in my house"},
{"file": "house.jpg", "description": "my house"},
{"file": "sky.jpg", "description": "sky over my house"}]
photo-list.html
<ul>
<li ng-repeat="photo in photos ">
<a href="#/photos/{{ $index }}">
<img ng-src="images/thumb/{{photo.file}}" alt="{{photo.description}}" />
</a>
</li>
</ul>
EDIT 1, Defer solution:
.run(function($http, $q) {
var deferred = $q.defer();
$http.get('photos.php')//load model with delay
.success(function(json) {
console.log(json);
photos = json; ///THE PROBLEM!! if photos.php is slow DON'T update the view!
deferred.resolve(json);//THE SOLUTION!
});
photos = deferred.promise;
})
EDIT 2, Service solution:
...
//require angular-resource.min.js
angular.module('photoApp.service', ['ngResource']).factory('photoList', function($resource) {
var Res = $resource('photos.php', {},
{
query: {method:'GET', params:{}, isArray:true}
});
return Res;
});
var photoAppModule = angular.module('photoApp', ['photoApp.service']);
...
.run(function($http, photoList) {
photos = photoList.query();
})
...
The short answer is this:
.controller('listCtrl', ['$scope', '$timeout', function($scope, $timeout) {
$timeout(function () {
$scope.photos = photos;
}, 0);
}]);
The long answer is: Please don't mix regular javascript and angular like this. Re-write your code so that angular knows what's going on at all times.
var photoAppModule = angular.module('photoApp', []);
photoAppModule.config(function($routeProvider) {
$routeProvider.when('/photos', {
templateUrl: 'photo-list.html',
controller: 'listCtrl'
});
$routeProvider.otherwise({redirectTo: '/photos'});
});
photoAppModule.controller('listCtrl', ['$scope', function($scope) {
$scope.photos = {};
$http.get('photos.php') // load model with delay
.success(function(json) {
$scope.photos = json; // No more problems
});
}]);
use broadcast
//service
var mydata = [];
this.update = function(){
$http.get(url).success(function(data){
mydata = data;
broadcastMe();
});
};
this.broadcastMe = function(){
$rootScope.$broadcast('mybroadcast');
};
//controller
$scope.$on('mybroadcast', function(){
$scope.mydata = service.mydata;
};
http://bresleveloper.blogspot.co.il/
EDIT:couple of days ago i've learned the best practice
http://bresleveloper.blogspot.co.il/2013/08/breslevelopers-angularjs-tutorial.html
I think you're better off using high level angular services for data transfer, also look into promises and services:
http://docs.angularjs.org/api/ng.$q
You need to bind an element in your view to a property (simple or object) of your $scope object. Once the $scope object is updated the view should be updated on its own. That is the beauty of AngularJS.
EDIT:
Please register your controller as
photoAppModule.controller('listCtrl', function($scope){
$scope.photos = photos;
});
If photos variable is not available, then you might have to create a service with the variable and inject in the controller.

Resources