I've got the following error messages in the console:
http://localhost/web/js/text.js
404 Not Found
if a delete text! in "text!templates/collector/indexTemplate.html" form collector_index.js, I've got the following error message:
http://localhost/web/js/templates/collector/indexTemplate.html.js
404 Not Found
main.js
require.config({
paths: {
html5shiv: "libs/html5shiv",
jquery: "http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min",
jqueryui: "http://code.jquery.com/ui/1.10.3/jquery-ui",
tablesorter: "libs/jquery.tablesorter.min",
script: "script",
underscore: "libs/underscore.min", /*"http://underscorejs.org/underscore",*/
backbone: "libs/backbone.min", /*"http://backbonejs.org/backbone-min",*/
utils: "utils",
// Collector
collectorModel: "models/collectorModel",
collectorCollection: "collectorCollection",
collectorRouter: "collectorRouter",
// Views
index: "views/collector/collector_index",
row: "views/collector/collector_row",
},
shim: {
jqueryui: {
deps: ["jquery"],
exports: "Jqueryui"
},
tablesorter: {
deps: ["jquery"],
exports: "TableSorter"
},
script: {
deps: ["jquery"],
exports: "Script"
},
underscore: {
exports: "_"
},
backbone: {
deps: ["underscore", "jquery"],
exports: "Backbone"
}
}
});
require(....
indexTemplate.html
<script type="text/template" id="indexTemplate">
<table class="tables">
<thead>
<tr>
<th>Name</th>
<th>Role</th>
</tr>
</thead>
<tbody></tbody>
</table>
<a class="btns" href="#collector/new">New Collector</a>
</script>
collector_index.js
define([
"backbone",
"underscore",
"row",
"text!templates/collector/indexTemplate.html"
], function (Backbone, _, CollectorRowView) {
var CollectorIndexView = Backbone.View.extend({
initialize: function (options) {
this.collectors = options.collectors;
this.collectors.bind('reset', this.addAll, this);
},
// populate the html to the dom
render: function () {
this.$el.html($('#indexTemplate').html());
this.addAll();
return this;
},
addAll: function () {
// clear out the container each time you render index
this.$el.find('tbody').children().remove();
_.each(this.collectors.models, $.proxy(this, 'addOne'));
},
addOne: function (collector) {
var view = new CollectorRowView({collectors: this.collectors, collector: collector});
this.$el.find("tbody").append(view.render().el);
}
});
return CollectorIndexView;
});
Directory structure:
js
views
main.js
...
templates
collector
indexTemplates.html
main.js
Thanks.
Not sure is this a typo or not but you have indexTemplates.html in your collector folder and indexTemplate.html in your define().
First make sure that you the text.js plugin in the same folder where your main.js is. Create a new entry in the main.js:
'templates': '../templates'
The template file itself can be a plain .html without the .js extension, and you should be able to reference it by:
var template = require("text!templates/collector/indexTemplate.html")
or in define() if your prefer that way.
Related
The best example to illustrate what I am trying to develop is a desktop email application.
On the left there is a vertical menu (on a quasar q-drawer).
Next, also on the left, there is a mailing list (on a quasar q-list within a q-drawer).
When each item is selected, the corresponding content is displayed on the right (on a quasar q-page).
Expected operation:
The list is loaded once and when I successively select the various items in the list, only the content on the right should be used and the content updated according to the id sent as a parameter in the request.
Note that the list component is only rendered once; that is, it is not rendered again each time a item is selected from the list and remains visible while the content is displayed on the right
The problem:
When I select the first item in the mailing list it works correctly and as expected, the mail content is displayed on the q-page.
When I select a second item from the list it doesn't work anymore and the following error is displayed on the console:
Uncaught (in promise) NavigationDuplicated {_name:
"NavigationDuplicated", name: "NavigationDuplicated", message:
"Navigating to current location ("/mailcontent") is not allowed",
stack: "Error at new NavigationDuplicated
(webpack-int…node_modules/vue/dist/vue.runtime.esm.js:1853:26)"}
I would appreciate suggestions on how to resolve this issue.
The following code is intended to illustrate the problem in the main part:
Routes: secondlayout is the child of another layout
const routes = [
{
path: "/index",
component: () => import("layouts/AppLayout.vue"),
children: [
{ path: "/home", component: () => import("pages/Home.vue") },
{
path: "secondlayout",
component: () => import("Layouts/MailsPlace.vue"),
children: [
{ path: "/mailcontent", name: 'mailcontent', component: () => import("pages/MailContent.vue") },
]
}
]
}
];
Second layout where the email application (list and content) is rendered with q-drawer and router-view
<template>
<q-layout view="lhh LpR lff" container class=" myclass shadow-2 window-height" >
<q-drawer
style="full-height"
v-model="drawerLeft"
:width="500"
:breakpoint="700"
elevated
content-class="bg-grey-1"
>
<q-scroll-area
class="fit"
style="margin-top:80px">
<q-list separator padding>
<q-separator />
<list-mails
v-for="(mail, index) in mails"
:mail="mail"
:key="mail.id_mail"
:id="index">
</list-mails>
<q-separator />
</q-list>
</q-scroll-area>
</q-drawer>
<q-page-container>
<router-view></router-view>
</q-page-container>
</template>
<script>
export default {
data () {
return {
mails: {},
drawerRight: false,
}
},
/* watch: {
$route(to, from) {
console.log('after', this.$route.path);
}
},
beforeRouteUpdate(to, from, next) {
console.log('before', this.$route.path);
next();
},*/
components: {
'list-mails': require("pages/ListMails.vue").default,
},
created: function() {
this.listMails()
},
methods: {
listMails(){
this.$axios.get("/listmails")
.then(response => {
if (response.data.success) {
this.mails = response.data.mails.data;
} else {
showErrorNotify('msg');
}
})
.catch(error => {
showErrorMessage(error.message);
});
}
}
</script>
Mail list item with mailitemclick method
<template>
<q-item
clickable
v-ripple
exact
#click="mailitemclick(mail.id_mail)"
>
<q-item-section>
<q-item-label side lines="2"> {{ mail.title_mail }}</q-item-label>
</q-item-section>
</q-item>
</template>
<script>
export default {
props: ["mail"],
methods:{
mailitemclick(id){
this.$router.push({
name: 'mailcontent',
params: {id:id}
});
}
}
}
</script>
Mail content
<template>
<q-page class="fit row wrap justify-center tems-start content-start" style="overflow: hidden;">
<div style="padding:5px; margin:0px 0px 20px 0px; min-width: 650px; max-width: 700px;" >
<q-item>
<q-item-label class="titulo"> {{ mail.title_mail }} </q-item-label>
<div v-html="mail.content_mail"></div>
</q-item>
</div>
</q-page>
</template>
<script>
export default {
name: 'mailcontent',
data() {
return {
mail: {},
};
},
created() {
this.$axios.get(`/mailcontent/${this.$route.params.id}`)
.then(response => {
if (response.data.success) {
this.mail = response.data.mail[0])
} else {
showErrorNotify('msg');
}
})
.catch(error => {
showErrorMessage(error.message);
});
}
}
</script>
This happened to me when I had a router-link pointing to the same route. e.g. /products/1.
The user is able to click on the products, but if a product was
already clicked (and the component view was already loaded) and the
user attempts to click it again, the error/warning shows in the
console.
You can solve this by adding catch block.
methods: {
mailitemclick(id) {
this.$router.push({
name: 'mailcontent',
params: {'id': id}
}).catch(err => {});
}
},
But in the mail-content, you need to use watch for calling function and in mounted for first-time calling.
Temp Example -
data() {
return {
mail: {},
test_mails: {
12: {
content_mail: '<div>test 12<div>'
},
122:{
content_mail: '<div>test 122<div>'
}
}
}
},
mounted() {
this.mail = this.test_mails[this.$route.params.id]
},
watch:{
'$route':function () {
this.mail = this.test_mails[this.$route.params.id]
}
}
OR
You can use :to in list-mail to avoild click and catch -
<q-item
clickable
v-ripple
exact
:to="'/mailcontent/'+mail.id_mail"
>
<q-item-section>
<q-item-label side lines="2"> {{ mail.title_mail }}</q-item-label>
</q-item-section>
</q-item>
children: [
{ path: '', component: () => import('pages/Index.vue') },
{
path: "secondlayout",
component: () => import("layouts/mail-place.vue"),
children: [
{ path: "/mailcontent/:id", name: 'mailcontent', component: () => import("pages/mail-content.vue") },
]
}
]
Given a Laravel 5.5 project, I want to use the "single file component" of the vue-i18n plugin. Documentation. It seems simple, but I can't get it to work.
app.js
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
const i18n = new VueI18n({
locale: 'en',
messages: {
"en": {
"word1": "hello world!"
}
}
})
Vue.component('test', require('./components/test.vue'));
const app = new Vue({ i18n, el: '#apps'});
components/test.vue
<template>
{{ $t('word1') }}
{{ $t('word2') }}
</template>
<i18n>
{
"en": {
"word2": "does this work?"
}
}
</i18n>
<script>
export default {
name: "test"
data() {
return {
locale: 'en'
}
},
mounted() {},
watch: {
locale (val) {
this.$i18n.locale = val
}
}
}
</script>
word1 is being replaced, however word2 is not. Placing bad syntax between the i18n-tags in the vue file, does NOT result in an error while compiling the files (npm run dev). This makes sense, because I'm missing the:
Taken from the documentation
module.exports = {
// ...
module: {
rules: [
...
This is supposed to go in the Webpack configuration. But, where is this file in laravel? All I can find is the webpack.mix.js, but placing this code in there, does not do much... Also making it mix.module.exports does not do the trick. Searching led me to this topic, but i'm not sure if he's asking the same as I am.
The problem: the i18n-tags aren't loaded. The solution is to add the code from the documentation.
My question: Where do I add this code?
To anyone stumbling upon the same problem, I proposed a change in the documentation:
https://github.com/kazupon/vue-i18n/pull/237
Laravel mix has its own rules for .vue files. To add the vue-i18n-loader, add the following to webpack.mix.js
mix.webpackConfig({
// ...
module: {
rules: [
{
// Rules are copied from laravel-mix#1.5.1 /src/builder/webpack-rules.js and manually merged with the ia8n-loader. Make sure to update the rules to the latest found in webpack-rules.js
test: /\.vue$/,
loader: 'vue-loader',
exclude: /bower_components/,
options: {
// extractCSS: Config.extractVueStyles,
loaders: Config.extractVueStyles ? {
js: {
loader: 'babel-loader',
options: Config.babel()
},
scss: vueExtractPlugin.extract({
use: 'css-loader!sass-loader',
fallback: 'vue-style-loader'
}),
sass: vueExtractPlugin.extract({
use: 'css-loader!sass-loader?indentedSyntax',
fallback: 'vue-style-loader'
}),
css: vueExtractPlugin.extract({
use: 'css-loader',
fallback: 'vue-style-loader'
}),
stylus: vueExtractPlugin.extract({
use: 'css-loader!stylus-loader?paths[]=node_modules',
fallback: 'vue-style-loader'
}),
less: vueExtractPlugin.extract({
use: 'css-loader!less-loader',
fallback: 'vue-style-loader'
}),
i18n: '#kazupon/vue-i18n-loader',
} : {
js: {
loader: 'babel-loader',
options: Config.babel()
},
i18n: '#kazupon/vue-i18n-loader',
},
postcss: Config.postCss,
preLoaders: Config.vue.preLoaders,
postLoaders: Config.vue.postLoaders,
esModule: Config.vue.esModule
}
},
// ...
]
},
// ...
});
I have a site with stocks. I would like to add typeahead functionality to my bootstrap template. Since there are about 5000 stocks and will be even more in the future. I am using haystack with whoosh index. I should be using remote version of typeahead.js, but it is not working. Could you please take a look and tell me what am I missing?
<script type="text/javascript">
var stocks = new Bloodhound({
datumTokenizer: function (datum) {
return Bloodhound.tokenizers.whitespace(datum.name);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 5,
remote: {
url: "/search/autocomplete/",
replace: function(url, query) {
return url + "?q=" + query;
},
filter: function(stocks) {
return $.map(stocks, function(data) {
return {
tokens: data.tokens,
symbol: data.symbol,
name: data.name
}
});
}
}
});
stocks.initialize();
$('.typeahead').typeahead(null, {
name: 'stocks',
displayKey: 'name',
minLength: 1, // send AJAX request only after user type in at least X characters
source: stocks.ttAdapter()
});
</script>
This is my form
<form class="input-prepend" method="get" action="/search/">
<div id="remote">
<button type="submit" class="btn">Search</button>
<input type="text" class="typeahead" id="id_q" placeholder="Stock symbol or name" autocomplete="off" name="q">
</div>
</form>
Urls.py
url(r'^search/autocomplete/', 'stocks.views.autocomplete'),
url(r'^search/', include('haystack.urls')),
autocomplete view
from haystack.query import SearchQuerySet
import json
def autocomplete(request):
sqs = SearchQuerySet().autocomplete(content_auto=request.GET.get('q', ''))[:5]
array = []
for result in sqs:
data = {"symbol": str(result.symbol),
"name": str(result.name),
"tokens": str(result.name).split()}
array.insert(0, data)
return HttpResponse(json.dumps(array), content_type='application/json')
json response:
[{"tokens": ["Arbor", "Realty", "Trus"], "symbol": "ABR", "name": "Arbor Realty Trus"}, {"tokens": ["ABM", "Industries", "In"], "symbol": "ABM", "name": "ABM Industries In"}, {"tokens": ["AmerisourceBergen"], "symbol": "ABC", "name": "AmerisourceBergen"}, {"tokens": ["ABB", "Ltd", "Common", "St"], "symbol": "ABB", "name": "ABB Ltd Common St"}, {"tokens": ["Allianceberstein"], "symbol": "AB", "name": "Allianceberstein "}]
This is my domain name: digrin.com and this is autocomplete url.
What am I missing?
I can see two problems:
1) Your script declaration is missing a type attribute:
<script src="http://code.jquery.com/jquery-1.11.0.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.js"></script>
<script type='text/javascript' src="http://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"></script>
add "type='text/javascript'" to the script declarations for jquery and bootstrap.
A more modern way of declaring your script tags can be found here.
2) To initialise Typeahead you need to place the code into your jQuery ready method i.e.
$(function(){
var stocks = new Bloodhound({
datumTokenizer: function (datum) {
return Bloodhound.tokenizers.whitespace(datum.name);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 5,
remote: {
url: "/search/autocomplete/",
replace: function(url, query) {
return url + "?q=" + query;
},
filter: function(stocks) {
return $.map(stocks, function(data) {
return {
tokens: data.tokens,
symbol: data.symbol,
name: data.name
}
});
}
}
});
stocks.initialize();
$('.typeahead').typeahead(null, {
name: 'stocks',
displayKey: 'name',
minLength: 1, // send AJAX request only after user type in at least X characters
source: stocks.ttAdapter()
});
});
As it is currently the typeahead code wont get loaded.
Despite my best efforts, I can't seem to get my testRunner.html to acknowledge my tests when I run the testRunner.html page in the browser. I've confirmed that it pulls in the test files and runs through the expect but the test runner is still saying that zero passed and zero failed. I've also tried moving the mocha.run() command into the testRunner.html page as an inline script to no effect.
What have I configured incorrectly?
testRunner.html
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8" />
<title> Tests </title>
<link href = "../node_modules/mocha/mocha.css" rel = "stylesheet">
</head>
<body>
<div id="mocha"></div>
<script src="../node_modules/mocha/mocha.js"></script>
<script>
mocha.setup('bdd');
</script>
<script src = "../node_modules/requirejs/require.js" data-main = "test.config.js"></script>
</body>
</html>
test.config.js
require.config({
baseUrl: '../src/public/js',
paths: {
jquery: '//code.jquery.com/jquery-2.1.1.min',
chai: '/../../../node_modules/chai/chai',
underscore: '//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min',
backbone: '//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min',
marionette: 'http://marionettejs.com/downloads/backbone.marionette',
handlebars: '//cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.3.0/handlebars',
syphon: '//cdnjs.cloudflare.com/ajax/libs/backbone.syphon/0.4.1/backbone.syphon.min'
},
shim: {
underscore: {
exports: '_'
},
backbone: {
deps: ['jquery', 'underscore'],
exports: 'Backbone'
},
marionette: {
deps: ['backbone'],
exports: 'Marionette'
},
syphon: {
deps: ['backbone', 'marionette'],
exports: 'Backbone.Syphon'
},
handlebars: {
exports: 'Handlebars'
}
}
});
require([
'../../../test/src/appTest'
], function() {
if (typeof mochaPhantomJS !== "undefined") {
mochaPhantomJS.run();
}
else {
mocha.run();
}
});
appTest.js
define(['chai'], function(chai) {
describe('array', function() {
chai.expect(1+1).to.equal(2);
});
});
You need to put your test in an it call:
define(['chai'], function(chai) {
describe('array', function() {
it("1 + 1 = 2", function () {
chai.expect(1+1).to.equal(2);
});
});
});
This is wholly an issue with how you are using Mocha. RequireJS is not a factor at all here.
I'm playing around with ember.js and am stuck somehow finding out how to build up the structure the right way. I could follow all examples, but have some problems putting them all together.
I'm using require.js and handlebars.
My directory structure looks like this:
- app
- - controllers
- - css
- - helpers
- - lib
- - models
- - routes
- - templates
- - - partials
- - views
My application.js looks like this:
require.config({
paths:{
jquery:'lib/jquery-1.7.2',
handlebars:'lib/handlebars',
ember:'lib/ember',
ember_data:'lib/ember-data',
text:'lib/requireJS/text',
md5:'lib/md5',
spin:'lib/spin'
},
shim:{
'ember':{
deps:[ 'jquery', 'handlebars'],
exports:'Ember'
},
'ember_data':{
deps:[ 'ember'],
exports:'DS'
}
},
waitSeconds:15
});
define('application'
,[
// Routes
'routes/app_router'
// Controller
,'controllers/application_controller'
// Views
,'views/application_view'
,'views/category/category_list_view'
// Libraries
,'jquery'
,'handlebars'
,'ember'
,'ember_data'
,'spin'
]
, function (
// Router
Router
// Controller
,ApplicationController
// Views
,ApplicationView
,CategoryListView
// Models
,Category
,Product
)
{
return Ember.Application.create({
VERSION: '1.0.0'
,rootElement:'#main'
// Load Router
,Router:Router
// Load Controllers
,ApplicationController:ApplicationController
// Load associated Views
,ApplicationView:ApplicationView
,CategoryListView:CategoryListView
// Load Models
,Category:Category
,Product:Product
//Persistence Layer,using default RESTAdapter in ember-data.js.
,store:DS.Store.create({
revision:10
,adapter:DS.RESTAdapter.create({
bulkCommit:false
,serializer:DS.Serializer.create({
primaryKey:function (type) {
return type.pk;
}
})
,mappings:{
//categories:Category
}
,namespace:'api'
,url: "https://example.org"
})
})
,ready:function () {
}
});
}
);
Then my application controller
define(
'controllers/application_controller'
,['ember' ],
function () {
return Ember.Controller.extend({
init: function() {
}
});
}
);
The application view:
define('views/application_view', [
'text!templates/application.html',
'ember'
],
function(Application_markup) {
return Ember.View.extend({
template: Ember.Handlebars.compile( Application_markup ),
elementId: 'container',
didInsertElement: function() {
this.$().hide().show("slow");
}
});
}
);
And, finally, the application.html template
<div id="container">
<div id="header">
FOO BAR
</div>
<div id="navigation">
{{outlet mainNavigation}}
</div>
<div id="content">
</div>
<div id="footer">
</div>
</div>
What I am trying to do now is to include another template into the main application template (category_list). I guess I either have to do this in the HTML template itself, or in the application view - but in case of the latter one I don't know how to configure/parse/bind more than one template.
What is the best practice of building individual, independent, modular templates and to put them all together? Where exactly should this happen?
Or is this even a wrong approach of using ember.js?
Maybe one of you could make some things more clear to me.
Thanks.
EDIT #1
app_router.js
define('routes/app_router',
['ember' ],
function () {
return Em.Router.extend({
enableLogging:true, //useful for development
/* location property: 'hash': Uses URL fragment identifiers (like #/blog/1) for routing.
'history': Uses the browser's history.pushstate API for routing. Only works in modern browsers with pushstate support.
'none': Does not read or set the browser URL, but still allows for routing to happen. Useful for testing.*/
location:'hash',
/* location: 'history',
rootURL:'/app',*/
root:Ember.Route.extend({
index:Ember.Route.extend({
route:'/'
/*,connectOutlets:function (router) {
//Render application View ,sign in.
v = router.get('applicationController').get('view');
if (v) v.remove();
App.router.get('applicationController').set('loggedin', false);
router.get('applicationController').connectOutlet({name:'login', outletName:'loginform'});
router.get('loginController').enterLogin();
}*/
})
/*,contacts:Em.Route.extend({
route:'/contacts',
showContact:function (router, event) {
router.transitionTo('contacts.contact.index', event.context);
},
showNewContact:function (router) {
router.transitionTo('contacts.newContact', {});
},
logout:function (router) {
jQuery.ajax({
url:'/site/logout',
type:'POST',
success:function (response) {
if (!response.authenticated) {
router.get('applicationController').set('loggedin', false).get('view').remove();
router.transitionTo('root.index', {});
}
}
})
},
index:Em.Route.extend({
route:'/',
connectOutlets:function (router) {
if (router.get('applicationController').get('loggedin'))
router.get('applicationController').connectOutlet('contacts', App.store.findAll(App.Contact));
else router.transitionTo('root.index');
}
}),
contact:Em.Route.extend({
route:'/contact',
index:Em.Route.extend({
route:'/:contact_id',
deserialize:function (router, urlParams) {
return App.store.find(App.Contact, urlParams.contact_id);
debugger;
},
showEdit:function (router) {
router.transitionTo('contacts.contact.edit');
},
connectOutlets:function (router, context) {
if (router.get('applicationController').get('loggedin'))
router.get('contactsController').connectOutlet('contact', context);
else router.transitionTo('root.index');
}
}),
edit:Em.Route.extend({
route:'edit',
cancelEdit:function (router) {
router.transitionTo('contacts.contact.index');
},
connectOutlets:function (router) {
if (router.get('applicationController').get('loggedin')) {
var contactsController = router.get('contactsController');
contactsController.connectOutlet('editContact', router.get('contactController').get('content'));
router.get('editContactController').enterEditing();
} else router.transitionTo('root.index');
},
exit:function (router) {
router.get('editContactController').exitEditing();
}
})
}),
newContact:Em.Route.extend({
route:'/contacts/new',
cancelEdit:function (router) {
router.transitionTo('contacts.index');
},
connectOutlets:function (router) {
if (router.get('applicationController').get('loggedin')) {
router.get('contactsController').connectOutlet('editContact', {});
router.get('editContactController').enterEditing();
} else router.transitionTo('root.index');
},
exit:function (router) {
router.get('editContactController').exitEditing();
}
})
})*/
})
});
}
);
EDIT #2
I changed the router now as follow, but it does not do anything.
define('routes/apps_router', ['ember'],
function () {
return Em.Router.extend({
enableLogging:true
,location:'hash'
,map: function (match) {
match("/").to("CategoryList", function (match) {
match("/").to("mainNavigation");
});
}
,root:Ember.Route.extend({
index:Ember.Route.extend({
route:'/'
,renderTemplates: function() {
this.render('mainNavigation', {
into: 'CategoryList'
});
}
// ....
});
}
);
Kind regards,
Christopher
if you use the latest release of ember with v2 router, you can do something like this:
App.Router.map(function (match) {
match("/").to("categoryList", function (match) {
match("/").to("foo");
});
});
In your catergoryList template, put an {{outlet}} (you can optionally name it)
Then, your route for the template you want to insert into catergoryList will be like this:
App.fooRouter = Ember.Router.extend({
renderTemplates:function () {
this.render('foo', {
into:'catergoryList'
});
}
})
A good example of this in practice can be found here: https://github.com/sh4n3d4v15/ember-todos